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


__SCREAMING_SNAKE_CASE						=      logging.getLogger(__name__)




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







def 					__magic_name__(       UpperCAmelCase__ :       ModelArguments							,				UpperCAmelCase__ :       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_     :	Union[str, Any]					     =     logging.WARNING
						if model_args.verbose_logging:
												UpperCamelCase_     :	Dict					     =     logging.DEBUG
						elif trainer_utils.is_main_process(training_args.local_rank	):
												UpperCamelCase_     :	str					     =     logging.INFO
						logger.setLevel(UpperCAmelCase__	)




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







@dataclass
class     __snake_case			:
		a_          =					False
		a_          =					None
		a_          =					"|"
		a_          =					field(default_factory=_a	)
		a_          =					field(default_factory=_a	)
		a_          =					None




		@classmethod
		def 	_snake_case	(  cls					:int			,    _SCREAMING_SNAKE_CASE					:str)					->			Union[str, Any]:






								'''simple docstring'''






								if name == "librispeech":
														return cls()
								if name == "timit":
														return cls(
														    do_lower_case=_SCREAMING_SNAKE_CASE			,    translation_table=str.maketrans({"""-""": """ """})			,    )
								if name == "buckwalter":
														UpperCamelCase_     :	Optional[int]					     =     {
														    """-""": """ """,  # 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 	_snake_case	(  self					:Optional[int]			,    _SCREAMING_SNAKE_CASE					:str)					->			str:






								'''simple docstring'''






								if len(self.translation_table) > 0:
														UpperCamelCase_     :	Tuple					     =     text.translate(self.translation_table)
								if len(self.words_to_remove) == 0:
														UpperCamelCase_     :	List[str]					     =     """ """.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 	_snake_case	(  self					:Tuple			,    _SCREAMING_SNAKE_CASE					:ModelArguments)					->			WavaVecaProcessor:






								'''simple docstring'''






								UpperCamelCase_     :	Union[str, Any]					     =     WavaVecaFeatureExtractor.from_pretrained(
								    model_args.model_name_or_path			,    cache_dir=model_args.cache_dir)
								if self.vocab_file:
														UpperCamelCase_     :	Optional[int]					     =     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_     :	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(_SCREAMING_SNAKE_CASE			,    _SCREAMING_SNAKE_CASE)







@dataclass
class     __snake_case			:
		a_          =					42
		a_          =					True
		a_          =					None
		a_          =					None
		a_          =					None
		a_          =					None




		def __call__(  self					:Dict			,    _SCREAMING_SNAKE_CASE					:List[Dict[str, Union[List[int], torch.Tensor]]])					->			Dict[str, torch.Tensor]:






								'''simple docstring'''






								UpperCamelCase_     :	str					     =     [{"""input_values""": feature["""input_values"""]} for feature in features]
								UpperCamelCase_     :	Optional[int]					     =     [{"""input_ids""": feature["""labels"""]} for feature in features]

								UpperCamelCase_     :	Optional[int]					     =     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"""			,    )
								UpperCamelCase_     :	Tuple					     =     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
								UpperCamelCase_     :	Any					     =     labels_batch["""input_ids"""].masked_fill(labels_batch.attention_mask.ne(1)			,    -1_0_0)

								UpperCamelCase_     :	Any					     =     labels

								return batch







class     __snake_case			(    _a	):




		def 	_snake_case	(  self					:Tuple			,    _SCREAMING_SNAKE_CASE					:nn.Module			,    _SCREAMING_SNAKE_CASE					:Dict[str, Union[torch.Tensor, Any]])					->			torch.Tensor:






								'''simple docstring'''






								model.train()
								UpperCamelCase_     :	List[Any]					     =     self._prepare_inputs(_SCREAMING_SNAKE_CASE)

								if self.use_amp:
														with autocast():
																				UpperCamelCase_     :	List[Any]					     =     self.compute_loss(_SCREAMING_SNAKE_CASE			,    _SCREAMING_SNAKE_CASE)
								else:
														UpperCamelCase_     :	Tuple					     =     self.compute_loss(_SCREAMING_SNAKE_CASE			,    _SCREAMING_SNAKE_CASE)

								if self.args.n_gpu > 1:
														if model.module.config.ctc_loss_reduction == "mean":
																				UpperCamelCase_     :	Optional[int]					     =     loss.mean()
														elif model.module.config.ctc_loss_reduction == "sum":
																				UpperCamelCase_     :	str					     =     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_     :	int					     =     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 					__magic_name__(       ):
						# 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_     :	int					     =     HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)	)

						UpperCamelCase_     ,UpperCamelCase_     ,UpperCamelCase_     :	Dict					     =     parser.parse_args_into_dataclasses()
						configure_logger(UpperCAmelCase__							,				UpperCAmelCase__	)

						UpperCamelCase_     :	List[Any]					     =     Orthography.from_name(data_args.orthography.lower()	)
						UpperCamelCase_     :	Optional[Any]					     =     orthography.create_processor(UpperCAmelCase__	)
						UpperCamelCase_     :	Optional[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_     :	Optional[int]					     =     datasets.load_dataset(
						    data_args.dataset_name							,				data_args.dataset_config_name							,				split=data_args.train_split_name	)
						UpperCamelCase_     :	List[str]					     =     datasets.load_dataset(
						    data_args.dataset_name							,				data_args.dataset_config_name							,				split=data_args.validation_split_name	)

						UpperCamelCase_     :	List[str]					     =     datasets.load_metric("""wer"""	)
						UpperCamelCase_     :	Optional[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(UpperCAmelCase__	) == 1	)
						UpperCamelCase_     :	Optional[int]					     =     re.compile(  # remove characters not in vocabulary
						    Rf"""[^\s{re.escape(UpperCAmelCase__	)}]"""							,				flags=re.IGNORECASE if processor.tokenizer.do_lower_case else 0							,				)
						UpperCamelCase_     :	Dict					     =     []

						def prepare_example(UpperCAmelCase__ :       Any	):  # TODO(elgeish) make use of multiprocessing?
												UpperCamelCase_     ,UpperCamelCase_     :	str					     =     librosa.load(example[data_args.speech_file_column]							,				sr=UpperCAmelCase__	)
												if data_args.max_duration_in_seconds is not None:
																		UpperCamelCase_     :	Optional[int]					     =     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_     :	Any					     =     vocabulary_text_cleaner.sub(""""""							,				UpperCAmelCase__	)
												if updated_text != example[data_args.target_text_column]:
																		text_updates.append((example[data_args.target_text_column], updated_text)	)
																		UpperCamelCase_     :	str					     =     updated_text
												return example

						UpperCamelCase_     :	Union[str, Any]					     =     train_dataset.map(UpperCAmelCase__							,				remove_columns=[data_args.speech_file_column]	)
						UpperCamelCase_     :	Optional[int]					     =     val_dataset.map(UpperCAmelCase__							,				remove_columns=[data_args.speech_file_column]	)

						if data_args.max_duration_in_seconds is not None:

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

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

						logger.warning(f"""Updated {len(UpperCAmelCase__	)} 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_     :	str					     =     None

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

						UpperCamelCase_     :	int					     =     train_dataset.map(
						    UpperCAmelCase__							,				batch_size=training_args.per_device_train_batch_size							,				batched=UpperCAmelCase__							,				num_proc=data_args.preprocessing_num_workers							,				)
						UpperCamelCase_     :	Optional[int]					     =     val_dataset.map(
						    UpperCAmelCase__							,				batch_size=training_args.per_device_train_batch_size							,				batched=UpperCAmelCase__							,				num_proc=data_args.preprocessing_num_workers							,				)

						UpperCamelCase_     :	Tuple					     =     DataCollatorCTCWithPadding(processor=UpperCAmelCase__							,				padding=UpperCAmelCase__	)

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

												UpperCamelCase_     :	str					     =     processor.tokenizer.pad_token_id

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

												UpperCamelCase_     :	List[Any]					     =     wer_metric.compute(predictions=UpperCAmelCase__							,				references=UpperCAmelCase__	)

												return {"wer": wer}

						if model_args.freeze_feature_extractor:
												model.freeze_feature_extractor()

						UpperCamelCase_     :	Optional[int]					     =     CTCTrainer(
						    model=UpperCAmelCase__							,				data_collator=UpperCAmelCase__							,				args=UpperCAmelCase__							,				compute_metrics=UpperCAmelCase__							,				train_dataset=UpperCAmelCase__							,				eval_dataset=UpperCAmelCase__							,				tokenizer=processor.feature_extractor							,				)

						trainer.train()


if __name__ == "__main__":
	main()






'''simple docstring'''


__SCREAMING_SNAKE_CASE						=      {hex(i)[2:]: i for i in range(16)}  # Use [:2] to strip off the leading '0x'
def 					__magic_name__(       UpperCAmelCase__ :       str	):
						UpperCamelCase_     :	str					     =     hex_string.strip().lower()
						if not hex_string:
												raise ValueError("""Empty string was passed to the function"""	)
						UpperCamelCase_     :	Dict					     =     hex_string[0] == """-"""
						if is_negative:
												UpperCamelCase_     :	List[str]					     =     hex_string[1:]
						if not all(char in hex_table for char in hex_string	):
												raise ValueError("""Non-hexadecimal value was passed to the function"""	)
						UpperCamelCase_     :	int					     =     0
						for char in hex_string:
												UpperCamelCase_     :	Any					     =     16 * decimal_number + hex_table[char]
						return -decimal_number if is_negative else decimal_number


if __name__ == "__main__":
	from doctest import testmod

	testmod()




