


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


snake_case__  				=			logging.getLogger(__name__)



@dataclass
class      snake_case__	:
				__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 			__SCREAMING_SNAKE_CASE							(					lowercase__	:ModelArguments   ,    lowercase__	:TrainingArguments					)							->	Union[str, Any]:
						logging.basicConfig(
						    format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'   ,    datefmt='%m/%d/%Y %H:%M:%S'   ,    handlers=[logging.StreamHandler(sys.stdout					)]   ,    )
						__magic_name__					:				str				=   logging.WARNING
						if model_args.verbose_logging:
												__magic_name__					:				Optional[Any]				=   logging.DEBUG
						elif trainer_utils.is_main_process(training_args.local_rank					):
												__magic_name__					:				str				=   logging.INFO
						logger.setLevel(lowercase__					)



@dataclass
class      snake_case__	:
				__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      snake_case__	:
				__lowerCAmelCase		=   False
				__lowerCAmelCase		=   None
				__lowerCAmelCase		=   "|"
				__lowerCAmelCase		=   field(default_factory=_A	)
				__lowerCAmelCase		=   field(default_factory=_A	)
				__lowerCAmelCase		=   None
				@classmethod
				def 			UpperCamelCase_    (	cls  ,   _UpperCAmelCase   ):




										"""simple docstring"""




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




										"""simple docstring"""




										if len(self.translation_table   ) > 0:
																__magic_name__					:				List[Any]				=   text.translate(self.translation_table   )
										if len(self.words_to_remove   ) == 0:
																__magic_name__					:				int				=   ' '.join(text.split()   )  # clean up whitespaces
										else:
																__magic_name__					:				Any				=   ' '.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   ):




										"""simple docstring"""




										__magic_name__					:				Optional[int]				=   WavaVecaFeatureExtractor.from_pretrained(
										    model_args.model_name_or_path  ,   cache_dir=model_args.cache_dir   )
										if self.vocab_file:
																__magic_name__					:				List[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:
																__magic_name__					:				Optional[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      snake_case__	:
				__lowerCAmelCase		=   42
				__lowerCAmelCase		=   True
				__lowerCAmelCase		=   None
				__lowerCAmelCase		=   None
				__lowerCAmelCase		=   None
				__lowerCAmelCase		=   None
				def __call__(	self  ,   _UpperCAmelCase   ):




										"""simple docstring"""




										__magic_name__					:				Dict				=   [{'input_values': feature['input_values']} for feature in features]
										__magic_name__					:				Any				=   [{'input_ids': feature['labels']} for feature in features]

										__magic_name__					:				int				=   self.processor.pad(
										    _UpperCAmelCase  ,   padding=self.padding  ,   max_length=self.max_length  ,   pad_to_multiple_of=self.pad_to_multiple_of  ,   return_tensors='pt'  ,   )
										__magic_name__					:				Dict				=   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
										__magic_name__					:				Dict				=   labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1   )  ,   -100   )

										__magic_name__					:				str				=   labels

										return batch






class      snake_case__	(   _A	):
				def 			UpperCamelCase_    (	self  ,   _UpperCAmelCase  ,   _UpperCAmelCase   ):




										"""simple docstring"""




										model.train()
										__magic_name__					:				Tuple				=   self._prepare_inputs(_UpperCAmelCase   )

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

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

						__magic_name__					:				List[str]				=   HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)					)

						__magic_name__		,			__magic_name__		,			__magic_name__					:				Union[str, Any]				=   parser.parse_args_into_dataclasses()
						configure_logger(lowercase__   ,    lowercase__					)

						__magic_name__					:				Optional[Any]				=   Orthography.from_name(data_args.orthography.lower()					)
						__magic_name__					:				Any				=   orthography.create_processor(lowercase__					)
						__magic_name__					:				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					)   ,    )

						__magic_name__					:				Any				=   datasets.load_dataset(
						    data_args.dataset_name   ,    data_args.dataset_config_name   ,    split=data_args.train_split_name					)
						__magic_name__					:				Any				=   datasets.load_dataset(
						    data_args.dataset_name   ,    data_args.dataset_config_name   ,    split=data_args.validation_split_name					)

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

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

						__magic_name__					:				str				=   train_dataset.map(lowercase__   ,    remove_columns=[data_args.speech_file_column]					)
						__magic_name__					:				Union[str, Any]				=   val_dataset.map(lowercase__   ,    remove_columns=[data_args.speech_file_column]					)

						if data_args.max_duration_in_seconds is not None:

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

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

						logger.warning(f"Updated {len(lowercase__					)} 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}\""					)
						__magic_name__					:				Any				=   None

						def prepare_dataset(lowercase__	:Optional[int]					):
												# 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}."

												__magic_name__					:				List[str]				=   processor(
												    audio=batch['speech']   ,    text=batch[data_args.target_text_column]   ,    sampling_rate=batch['sampling_rate'][0]					)
												batch.update(lowercase__					)
												return batch

						__magic_name__					:				int				=   train_dataset.map(
						    lowercase__   ,    batch_size=training_args.per_device_train_batch_size   ,    batched=lowercase__   ,    num_proc=data_args.preprocessing_num_workers   ,    )
						__magic_name__					:				Tuple				=   val_dataset.map(
						    lowercase__   ,    batch_size=training_args.per_device_train_batch_size   ,    batched=lowercase__   ,    num_proc=data_args.preprocessing_num_workers   ,    )

						__magic_name__					:				Tuple				=   DataCollatorCTCWithPadding(processor=lowercase__   ,    padding=lowercase__					)

						def compute_metrics(lowercase__	:Dict					):
												__magic_name__					:				List[Any]				=   pred.predictions
												__magic_name__					:				Optional[int]				=   np.argmax(lowercase__   ,    axis=-1					)

												__magic_name__					:				List[str]				=   processor.tokenizer.pad_token_id

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

												__magic_name__					:				List[str]				=   wer_metric.compute(predictions=lowercase__   ,    references=lowercase__					)

												return {"wer": wer}

						if model_args.freeze_feature_extractor:
												model.freeze_feature_extractor()

						__magic_name__					:				Union[str, Any]				=   CTCTrainer(
						    model=lowercase__   ,    data_collator=lowercase__   ,    args=lowercase__   ,    compute_metrics=lowercase__   ,    train_dataset=lowercase__   ,    eval_dataset=lowercase__   ,    tokenizer=processor.feature_extractor   ,    )

						trainer.train()


if __name__ == "__main__":
			main()






import math
def 			__SCREAMING_SNAKE_CASE							(					lowercase__	:int					)							->	list:
						if n <= 0:
												raise ValueError('Only positive integers have prime factors'					)
						__magic_name__					:				Union[str, Any]				=   []
						while n % 2 == 0:
												pf.append(2					)
												__magic_name__					:				Union[str, Any]				=   int(n / 2					)
						for i in range(3   ,    int(math.sqrt(lowercase__					)					) + 1   ,    2					):
												while n % i == 0:
																		pf.append(lowercase__					)
																		__magic_name__					:				List[str]				=   int(n / i					)
						if n > 2:
												pf.append(lowercase__					)
						return pf
def 			__SCREAMING_SNAKE_CASE							(					lowercase__	:int					)							->	int:
						if n <= 0:
												raise ValueError('Only positive numbers are accepted'					)
						__magic_name__					:				Union[str, Any]				=   1
						__magic_name__					:				Tuple				=   1
						while n % 2 == 0:
												temp += 1
												__magic_name__					:				Any				=   int(n / 2					)
						div *= temp
						for i in range(3   ,    int(math.sqrt(lowercase__					)					) + 1   ,    2					):
												__magic_name__					:				List[Any]				=   1
												while n % i == 0:
																		temp += 1
																		__magic_name__					:				Any				=   int(n / i					)
												div *= temp
						if n > 1:
												div *= 2
						return div
def 			__SCREAMING_SNAKE_CASE							(					lowercase__	:int					)							->	int:
						if n <= 0:
												raise ValueError('Only positive numbers are accepted'					)
						__magic_name__					:				int				=   1
						__magic_name__					:				List[str]				=   1
						while n % 2 == 0:
												temp += 1
												__magic_name__					:				List[Any]				=   int(n / 2					)
						if temp > 1:
												s *= (2**temp - 1) / (2 - 1)
						for i in range(3   ,    int(math.sqrt(lowercase__					)					) + 1   ,    2					):
												__magic_name__					:				int				=   1
												while n % i == 0:
																		temp += 1
																		__magic_name__					:				Optional[Any]				=   int(n / i					)
												if temp > 1:
																		s *= (i**temp - 1) / (i - 1)
						return int(lowercase__					)
def 			__SCREAMING_SNAKE_CASE							(					lowercase__	:int					)							->	int:
						__magic_name__					:				Dict				=   n
						for x in set(prime_factors(lowercase__					)					):
												s *= (x - 1) / x
						return int(lowercase__					)


if __name__ == "__main__":
			import doctest

			doctest.testmod()


