


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


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






def    a__       ( __lowercase   ,	__lowercase      )		->		Dict:
				logging.basicConfig(
				    format="%(asctime)s - %(levelname)s - %(name)s - %(message)s"   ,	datefmt="%m/%d/%Y %H:%M:%S"   ,	handlers=[logging.StreamHandler(sys.stdout      )]   ,	)
				_A         =	logging.WARNING
				if model_args.verbose_logging:
								_A         =	logging.DEBUG
				elif trainer_utils.is_main_process(training_args.local_rank      ):
								_A         =	logging.INFO
				logger.setLevel(__lowercase      )
@dataclass
class snake_case					:
		__UpperCamelCase							=	field(
		    default=_UpperCamelCase   , metadata={'help': 'The name of the dataset to use (via the datasets library).'})
		__UpperCamelCase							=	field(
		    default=_UpperCamelCase   , metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'})
		__UpperCamelCase							=	field(
		    default='train'   , metadata={
		        'help': 'The name of the training data set split to use (via the datasets library). Defaults to \'train\''
		    }   , )
		__UpperCamelCase							=	field(
		    default='validation'   , metadata={
		        'help': (
		            'The name of the validation data set split to use (via the datasets library). Defaults to \'validation\''
		        )
		    }   , )
		__UpperCamelCase							=	field(
		    default='text'   , metadata={'help': 'Column in the dataset that contains label (target text). Defaults to \'text\''}   , )
		__UpperCamelCase							=	field(
		    default='file'   , metadata={'help': 'Column in the dataset that contains speech file path. Defaults to \'file\''}   , )
		__UpperCamelCase							=	field(
		    default=_UpperCamelCase   , metadata={'help': 'Resample loaded audio to target feature extractor\'s sampling rate or not.'}   , )
		__UpperCamelCase							=	field(
		    default=_UpperCamelCase   , metadata={'help': 'Filters out examples longer than specified. Defaults to no filtering.'}   , )
		__UpperCamelCase							=	field(
		    default='librispeech'   , metadata={
		        'help': (
		            'Orthography used for normalization and tokenization: \'librispeech\' (default), \'timit\', or'
		            ' \'buckwalter\'.'
		        )
		    }   , )
		__UpperCamelCase							=	field(
		    default=_UpperCamelCase   , metadata={'help': 'Overwrite the cached preprocessed datasets or not.'})
		__UpperCamelCase							=	field(
		    default=_UpperCamelCase   , metadata={'help': 'The number of processes to use for the preprocessing.'}   , )





@dataclass
class snake_case					:
		__UpperCamelCase							=	False
		__UpperCamelCase							=	None
		__UpperCamelCase							=	"|"
		__UpperCamelCase							=	field(default_factory=_UpperCamelCase)
		__UpperCamelCase							=	field(default_factory=_UpperCamelCase)
		__UpperCamelCase							=	None







		@classmethod
		def        a_       (    cls					:				List[str]			,      a__					:				str						)				->  Any:





						'''simple docstring'''







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





						'''simple docstring'''







						if len(self.translation_table						) > 0:
										_A         =	text.translate(self.translation_table						)
						if len(self.words_to_remove						) == 0:
										_A         =	" ".join(text.split()						)  # clean up whitespaces
						else:
										_A         =	" ".join(w for w in text.split() if w not in self.words_to_remove						)  # and clean up whilespaces
						return text







		def        a_       (    self					:				Union[str, Any]			,      a__					:				ModelArguments						)				->  WavaVecaProcessor:





						'''simple docstring'''







						_A         =	WavaVecaFeatureExtractor.from_pretrained(
						    model_args.model_name_or_path			,      cache_dir=model_args.cache_dir						)
						if self.vocab_file:
										_A         =	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:
										_A         =	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 snake_case					:
		__UpperCamelCase							=	42
		__UpperCamelCase							=	True
		__UpperCamelCase							=	None
		__UpperCamelCase							=	None
		__UpperCamelCase							=	None
		__UpperCamelCase							=	None







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





						'''simple docstring'''







						_A         =	[{"input_values": feature["input_values"]} for feature in features]
						_A         =	[{"input_ids": feature["labels"]} for feature in features]

						_A         =	self.processor.pad(
						    a__			,      padding=self.padding			,      max_length=self.max_length			,      pad_to_multiple_of=self.pad_to_multiple_of			,      return_tensors="pt"			,      )
						_A         =	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
						_A         =	labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1						)			,      -1_00						)

						_A         =	labels

						return batch





class snake_case					(     _UpperCamelCase):







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





						'''simple docstring'''







						model.train()
						_A         =	self._prepare_inputs(a__						)

						if self.use_amp:
										with autocast():
														_A         =	self.compute_loss(a__			,      a__						)
						else:
										_A         =	self.compute_loss(a__			,      a__						)

						if self.args.n_gpu > 1:
										if model.module.config.ctc_loss_reduction == "mean":
														_A         =	loss.mean()
										elif model.module.config.ctc_loss_reduction == "sum":
														_A         =	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:
										_A         =	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    a__       ( )		->		List[str]:
				# 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.

				_A         =	HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)      )

				_A     ,						_A     ,						_A         =	parser.parse_args_into_dataclasses()
				configure_logger(__lowercase   ,	__lowercase      )

				_A         =	Orthography.from_name(data_args.orthography.lower()      )
				_A         =	orthography.create_processor(__lowercase      )
				_A         =	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      )   ,	)

				_A         =	datasets.load_dataset(
				    data_args.dataset_name   ,	data_args.dataset_config_name   ,	split=data_args.train_split_name      )
				_A         =	datasets.load_dataset(
				    data_args.dataset_name   ,	data_args.dataset_config_name   ,	split=data_args.validation_split_name      )

				_A         =	datasets.load_metric("wer"      )
				_A         =	processor.feature_extractor.sampling_rate if data_args.target_feature_extractor_sampling_rate else None
				_A         =	"".join(t for t in processor.tokenizer.get_vocab().keys() if len(__lowercase      ) == 1      )
				_A         =	re.compile(  # remove characters not in vocabulary
				    Rf"""[^\s{re.escape(__lowercase      )}]"""   ,	flags=re.IGNORECASE if processor.tokenizer.do_lower_case else 0   ,	)
				_A         =	[]

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

				_A         =	train_dataset.map(__lowercase   ,	remove_columns=[data_args.speech_file_column]      )
				_A         =	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      ):
												return example["duration_in_seconds"] <= data_args.max_duration_in_seconds

								_A         =	len(__lowercase      )
								_A         =	len(__lowercase      )
								_A         =	train_dataset.filter(__lowercase   ,	remove_columns=["duration_in_seconds"]      )
								_A         =	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}\""""      )
				_A         =	None

				def prepare_dataset(__lowercase      ):
								# 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}."""

								_A         =	processor(
								    audio=batch["speech"]   ,	text=batch[data_args.target_text_column]   ,	sampling_rate=batch["sampling_rate"][0]      )
								batch.update(__lowercase      )
								return batch

				_A         =	train_dataset.map(
				    __lowercase   ,	batch_size=training_args.per_device_train_batch_size   ,	batched=__lowercase   ,	num_proc=data_args.preprocessing_num_workers   ,	)
				_A         =	val_dataset.map(
				    __lowercase   ,	batch_size=training_args.per_device_train_batch_size   ,	batched=__lowercase   ,	num_proc=data_args.preprocessing_num_workers   ,	)

				_A         =	DataCollatorCTCWithPadding(processor=__lowercase   ,	padding=__lowercase      )

				def compute_metrics(__lowercase      ):
								_A         =	pred.predictions
								_A         =	np.argmax(__lowercase   ,	axis=-1      )

								_A         =	processor.tokenizer.pad_token_id

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

								_A         =	wer_metric.compute(predictions=__lowercase   ,	references=__lowercase      )

								return {"wer": wer}

				if model_args.freeze_feature_extractor:
								model.freeze_feature_extractor()

				_A         =	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()




def        __a     (    lowerCAmelCase_   :					int				)      -> int:






						'''simple docstring'''



						if number != int(lowerCAmelCase_				):
												raise ValueError("""factorial() only accepts integral values"""				)
						if number < 0:
												raise ValueError("""factorial() not defined for negative values"""				)
						UpperCAmelCase_=   1
						for i in range(1			,number + 1				):
												value *= i
						return value



def        __a     (    lowerCAmelCase_   :					int				)      -> int:






						'''simple docstring'''



						if not isinstance(lowerCAmelCase_			,lowerCAmelCase_				):
												raise ValueError("""factorial() only accepts integral values"""				)
						if n < 0:
												raise ValueError("""factorial() not defined for negative values"""				)
						return 1 if n == 0 or n == 1 else n * factorial(n - 1				)


if __name__ == "__main__":
	import doctest

	doctest.testmod()

	__A				    =						int(input('''Enter a positive integer: ''').strip() or 0)
	print(f'factorial{n} is {factorial(n)}')




