






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


__UpperCAmelCase										=		logging.getLogger(__name__)



@dataclass
class 						lowerCamelCase   :







		'''simple docstring'''



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





def   lowercase__   (  __snake_case					:							ModelArguments  , __snake_case					:							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						)]  , )
					UpperCAmelCase_					:   List[str]   =		logging.WARNING
					if model_args.verbose_logging:
										UpperCAmelCase_					:   Any   =		logging.DEBUG
					elif trainer_utils.is_main_process(training_args.local_rank						):
										UpperCAmelCase_					:   Tuple   =		logging.INFO
					logger.setLevel(__snake_case						)



@dataclass
class 						lowerCamelCase   :







		'''simple docstring'''



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





@dataclass
class 						lowerCamelCase   :







		'''simple docstring'''



		_snake_case					:					bool 		=						False
		_snake_case					:					Optional[str] 		=						None
		_snake_case					:					Optional[str] 		=						"|"
		_snake_case					:					Optional[Dict[str, str]] 		=						field(default_factory=_snake_case    )
		_snake_case					:					Optional[Set[str]] 		=						field(default_factory=_snake_case    )
		_snake_case					:					Optional[Callable[[str], str]] 		=						None



		@classmethod
		def       __UpperCAmelCase    (							cls       ,	_UpperCamelCase     )			->							int:
							if name == "librispeech":
												return cls()
							if name == "timit":
												return cls(
												    do_lower_case=_UpperCamelCase       ,	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(_UpperCamelCase     ).parent.joinpath('vocab/buckwalter.json'     )       ,	word_delimiter_token='/'       ,	translation_table=str.maketrans(_UpperCamelCase     )       ,	words_to_remove={'sil'}       ,	untransliterator=arabic.buckwalter.untransliterate       ,	)
							raise ValueError(f"Unsupported orthography: '{name}'."     )



		def       __UpperCAmelCase    (							self       ,	_UpperCamelCase     )			->							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_					:   List[str]   =		text.translate(self.translation_table     )
							if len(self.words_to_remove     ) == 0:
												UpperCAmelCase_					:   Optional[int]   =		' '.join(text.split()     )  # clean up whitespaces
							else:
												UpperCAmelCase_					:   Tuple   =		' '.join(w for w in text.split() if w not in self.words_to_remove     )  # and clean up whilespaces
							return text



		def       __UpperCAmelCase    (							self       ,	_UpperCamelCase     )			->							WavaVecaProcessor:
							UpperCAmelCase_					:   Optional[Any]   =		WavaVecaFeatureExtractor.from_pretrained(
							    model_args.model_name_or_path       ,	cache_dir=model_args.cache_dir     )
							if self.vocab_file:
												UpperCAmelCase_					:   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:
												UpperCAmelCase_					:   List[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(_UpperCamelCase       ,	_UpperCamelCase     )





@dataclass
class 						lowerCamelCase   :







		'''simple docstring'''



		_snake_case					:					WavaVecaProcessor
		_snake_case					:					Union[bool, str] 		=						True
		_snake_case					:					Optional[int] 		=						None
		_snake_case					:					Optional[int] 		=						None
		_snake_case					:					Optional[int] 		=						None
		_snake_case					:					Optional[int] 		=						None



		def __call__(							self       ,	_UpperCamelCase     )			->							Dict[str, torch.Tensor]:
							# split inputs and labels since they have to be of different lenghts and need
							# different padding methods
							UpperCAmelCase_					:   Dict   =		[{'input_values': feature['input_values']} for feature in features]
							UpperCAmelCase_					:   str   =		[{'input_ids': feature['labels']} for feature in features]

							UpperCAmelCase_					:   Optional[Any]   =		self.processor.pad(
							    _UpperCamelCase       ,	padding=self.padding       ,	max_length=self.max_length       ,	pad_to_multiple_of=self.pad_to_multiple_of       ,	return_tensors='pt'       ,	)
							UpperCAmelCase_					:   Optional[int]   =		self.processor.pad(
							    labels=_UpperCamelCase       ,	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[str]   =		labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1     )       ,	-1_0_0     )

							UpperCAmelCase_					:   Tuple   =		labels

							return batch





class 						lowerCamelCase   (_snake_case    ):







		'''simple docstring'''



		def       __UpperCAmelCase    (							self       ,	_UpperCamelCase       ,	_UpperCamelCase     )			->							torch.Tensor:
							model.train()
							UpperCAmelCase_					:   Optional[int]   =		self._prepare_inputs(_UpperCamelCase     )

							if self.use_amp:
												with autocast():
																	UpperCAmelCase_					:   Dict   =		self.compute_loss(_UpperCamelCase       ,	_UpperCamelCase     )
							else:
												UpperCAmelCase_					:   Optional[int]   =		self.compute_loss(_UpperCamelCase       ,	_UpperCamelCase     )

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

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

							return loss.detach()





def   lowercase__   (  ):


					'''simple docstring'''


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

					UpperCAmelCase_ ,						UpperCAmelCase_ ,						UpperCAmelCase_					:   List[Any]   =		parser.parse_args_into_dataclasses()
					configure_logger(__snake_case  , __snake_case						)

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

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

					def prepare_example(__snake_case					:							Union[str, Any]						):  # TODO(elgeish) make use of multiprocessing?
										UpperCAmelCase_ ,						UpperCAmelCase_					:   Union[str, Any]   =		librosa.load(example[data_args.speech_file_column]  , sr=__snake_case						)
										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_					:   str   =		orthography.preprocess_for_training(example[data_args.target_text_column]						)
										UpperCAmelCase_					:   Tuple   =		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)						)
															UpperCAmelCase_					:   List[Any]   =		updated_text
										return example

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

										UpperCAmelCase_					:   Optional[int]   =		len(__snake_case						)
										UpperCAmelCase_					:   Dict   =		len(__snake_case						)
										UpperCAmelCase_					:   Optional[Any]   =		train_dataset.filter(__snake_case  , remove_columns=['duration_in_seconds']						)
										UpperCAmelCase_					:   Optional[int]   =		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}\""						)
					UpperCAmelCase_					:   Dict   =		None

					def prepare_dataset(__snake_case					:							Union[str, 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_					:   int   =		processor(
										    audio=batch['speech']  , text=batch[data_args.target_text_column]  , sampling_rate=batch['sampling_rate'][0]						)
										batch.update(__snake_case						)
										return batch

					UpperCAmelCase_					:   Any   =		train_dataset.map(
					    __snake_case  , batch_size=training_args.per_device_train_batch_size  , batched=__snake_case  , num_proc=data_args.preprocessing_num_workers  , )
					UpperCAmelCase_					:   Dict   =		val_dataset.map(
					    __snake_case  , batch_size=training_args.per_device_train_batch_size  , batched=__snake_case  , num_proc=data_args.preprocessing_num_workers  , )

					UpperCAmelCase_					:   Dict   =		DataCollatorCTCWithPadding(processor=__snake_case  , padding=__snake_case						)

					def compute_metrics(__snake_case					:							List[str]						):
										UpperCAmelCase_					:   Any   =		pred.predictions
										UpperCAmelCase_					:   Tuple   =		np.argmax(__snake_case  , axis=-1						)

										UpperCAmelCase_					:   Any   =		processor.tokenizer.pad_token_id

										UpperCAmelCase_					:   Union[str, Any]   =		processor.batch_decode(__snake_case						)
										# we do not want to group tokens when computing the metrics
										UpperCAmelCase_					:   Optional[Any]   =		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						)}\""						)

										UpperCAmelCase_					:   int   =		wer_metric.compute(predictions=__snake_case  , references=__snake_case						)

										return {"wer": wer}

					if model_args.freeze_feature_extractor:
										model.freeze_feature_extractor()

					UpperCAmelCase_					:   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()














import torch.nn as nn

from .imports import is_fpa_available


if is_fpa_available():
		import transformer_engine.pytorch as te




def   lowercase__   (  __snake_case					:							List[str]  , __snake_case					:							List[Any]=True  , __snake_case					:							str=True  , __snake_case					:							Tuple=True						):


					'''simple docstring'''


					if not is_fpa_available():
										raise ImportError('Using `convert_model` requires transformer_engine to be installed.'						)
					for name, module in model.named_children():
										if isinstance(__snake_case  , nn.Linear						) and to_transformer_engine and _convert_linear:
															# Return early if the linear layer weights are not multiples of 16
															if any(p % 16 != 0 for p in module.weight.shape						):
																				return
															UpperCAmelCase_					:   Optional[int]   =		module.bias is not None
															UpperCAmelCase_					:   Optional[int]   =		te.Linear(
															    module.in_features  , module.out_features  , bias=__snake_case  , params_dtype=module.weight.dtype						)
															UpperCAmelCase_					:   List[str]   =		module.weight.data.clone()
															if has_bias:
																				UpperCAmelCase_					:   List[Any]   =		module.bias.data.clone()

															setattr(__snake_case  , __snake_case  , __snake_case						)
										elif isinstance(__snake_case  , nn.LayerNorm						) and to_transformer_engine and _convert_ln:
															UpperCAmelCase_					:   int   =		te.LayerNorm(module.normalized_shape[0]  , eps=module.eps  , params_dtype=module.weight.dtype						)
															UpperCAmelCase_					:   Any   =		module.weight.data.clone()
															UpperCAmelCase_					:   Any   =		module.bias.data.clone()

															setattr(__snake_case  , __snake_case  , __snake_case						)
										elif isinstance(__snake_case  , te.Linear						) and not to_transformer_engine and _convert_linear:
															UpperCAmelCase_					:   int   =		module.bias is not None
															UpperCAmelCase_					:   Tuple   =		nn.Linear(
															    module.in_features  , module.out_features  , bias=__snake_case  , params_dtype=module.weight.dtype						)
															UpperCAmelCase_					:   str   =		module.weight.data.clone()
															if has_bias:
																				UpperCAmelCase_					:   Dict   =		module.bias.data.clone()

															setattr(__snake_case  , __snake_case  , __snake_case						)
										elif isinstance(__snake_case  , te.LayerNorm						) and not to_transformer_engine and _convert_ln:
															UpperCAmelCase_					:   List[Any]   =		nn.LayerNorm(module.normalized_shape[0]  , eps=module.eps  , params_dtype=module.weight.dtype						)
															UpperCAmelCase_					:   List[str]   =		module.weight.data.clone()
															UpperCAmelCase_					:   Tuple   =		module.bias.data.clone()

															setattr(__snake_case  , __snake_case  , __snake_case						)
										else:
															convert_model(
															    __snake_case  , to_transformer_engine=__snake_case  , _convert_linear=_convert_linear  , _convert_ln=_convert_ln  , )






def   lowercase__   (  __snake_case					:							List[Any]						):


					'''simple docstring'''


					if not is_fpa_available():
										raise ImportError('Using `has_transformer_engine_layers` requires transformer_engine to be installed.'						)
					for m in model.modules():
										if isinstance(__snake_case  , (te.LayerNorm, te.Linear)						):
															return True
					return False






