
"""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    __lowerCamelCase     :
				a__:			str									=						field(
				    metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} )
				a__:			Optional[str]									=						field(
				    default=lowerCAmelCase	,  metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'}	,  )
				a__:			Optional[bool]									=						field(
				    default=lowerCAmelCase	,  metadata={'help': 'Whether to freeze the feature extractor layers of the model.'} )
				a__:			Optional[bool]									=						field(
				    default=lowerCAmelCase	,  metadata={'help': 'Whether to log verbose messages or not.'}	,  )






def    lowercase	(  lowerCAmelCase__  ,lowerCAmelCase__	):
			logging.basicConfig(
			    format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s'''  ,datefmt='''%m/%d/%Y %H:%M:%S'''  ,handlers=[logging.StreamHandler(sys.stdout	)]  ,)
			lowerCamelCase_ 		=     logging.WARNING
			if model_args.verbose_logging:
						lowerCamelCase_ 		=     logging.DEBUG
			elif trainer_utils.is_main_process(training_args.local_rank	):
						lowerCamelCase_ 		=     logging.INFO
			logger.setLevel(lowerCAmelCase__	)




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




@dataclass
class    __lowerCamelCase     :
				a__:			bool									=						False
				a__:			Optional[str]									=						None
				a__:			Optional[str]									=						"|"
				a__:			Optional[Dict[str, str]]									=						field(default_factory=lowerCAmelCase )
				a__:			Optional[Set[str]]									=						field(default_factory=lowerCAmelCase )
				a__:			Optional[Callable[[str], str]]									=						None




				@classmethod
				def 					UpperCAmelCase__	(							cls       ,	UpperCAmelCase      ):
							if name == "librispeech":
										return cls()
							if name == "timit":
										return cls(
										    do_lower_case=UpperCAmelCase       ,	translation_table=str.maketrans({'''-''': ''' '''}      )       ,	)
							if name == "buckwalter":
										lowerCamelCase_ 		=     {
										    '''-''': ''' ''',  # 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      ):
							# TODO(elgeish) return a pipeline (e.g., from jiwer) instead? Or rely on branch predictor as is
							if len(self.translation_table      ) > 0:
										lowerCamelCase_ 		=     text.translate(self.translation_table      )
							if len(self.words_to_remove      ) == 0:
										lowerCamelCase_ 		=     ''' '''.join(text.split()      )  # clean up whitespaces
							else:
										lowerCamelCase_ 		=     ''' '''.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      ):
							lowerCamelCase_ 		=     WavaVecaFeatureExtractor.from_pretrained(
							    model_args.model_name_or_path       ,	cache_dir=model_args.cache_dir      )
							if self.vocab_file:
										lowerCamelCase_ 		=     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:
										lowerCamelCase_ 		=     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     :
				a__:			WavaVecaProcessor
				a__:			Union[bool, str]									=						True
				a__:			Optional[int]									=						None
				a__:			Optional[int]									=						None
				a__:			Optional[int]									=						None
				a__:			Optional[int]									=						None




				def __call__(							self       ,	UpperCAmelCase      ):
							# split inputs and labels since they have to be of different lenghts and need
							# different padding methods
							lowerCamelCase_ 		=     [{'''input_values''': feature['''input_values''']} for feature in features]
							lowerCamelCase_ 		=     [{'''input_ids''': feature['''labels''']} for feature in features]

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

							lowerCamelCase_ 		=     labels

							return batch




class    __lowerCamelCase     (   lowerCAmelCase ):




				def 					UpperCAmelCase__	(							self       ,	UpperCAmelCase       ,	UpperCAmelCase      ):
							model.train()
							lowerCamelCase_ 		=     self._prepare_inputs(UpperCAmelCase      )

							if self.use_amp:
										with autocast():
													lowerCamelCase_ 		=     self.compute_loss(UpperCAmelCase       ,	UpperCAmelCase      )
							else:
										lowerCamelCase_ 		=     self.compute_loss(UpperCAmelCase       ,	UpperCAmelCase      )

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

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

			lowerCamelCase_		,   lowerCamelCase_		,   lowerCamelCase_ 		=     parser.parse_args_into_dataclasses()
			configure_logger(lowerCAmelCase__  ,lowerCAmelCase__	)

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

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

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

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

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

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

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

						lowerCamelCase_ 		=     processor(
						    audio=batch['''speech''']  ,text=batch[data_args.target_text_column]  ,sampling_rate=batch['''sampling_rate'''][0]	)
						batch.update(lowerCAmelCase__	)
						return batch

			lowerCamelCase_ 		=     train_dataset.map(
			    lowerCAmelCase__  ,batch_size=training_args.per_device_train_batch_size  ,batched=lowerCAmelCase__  ,num_proc=data_args.preprocessing_num_workers  ,)
			lowerCamelCase_ 		=     val_dataset.map(
			    lowerCAmelCase__  ,batch_size=training_args.per_device_train_batch_size  ,batched=lowerCAmelCase__  ,num_proc=data_args.preprocessing_num_workers  ,)

			lowerCamelCase_ 		=     DataCollatorCTCWithPadding(processor=lowerCAmelCase__  ,padding=lowerCAmelCase__	)

			def compute_metrics(lowerCAmelCase__	):
						lowerCamelCase_ 		=     pred.predictions
						lowerCamelCase_ 		=     np.argmax(lowerCAmelCase__  ,axis=-1	)

						lowerCamelCase_ 		=     processor.tokenizer.pad_token_id

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

						lowerCamelCase_ 		=     wer_metric.compute(predictions=lowerCAmelCase__  ,references=lowerCAmelCase__	)

						return {"wer": wer}

			if model_args.freeze_feature_extractor:
						model.freeze_feature_extractor()

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





"""simple docstring"""


import warnings
from collections.abc import Callable
from typing import Any

import numpy
from matplotlib import pyplot

A_						       =				0.25 + 0.0J
A_						       =				-0.4 + 0.6J
A_						       =				-0.1 + 0.651J
A_						       =				-2.0
A_						       =				56
A_						       =				2.0
A_						       =				666






def    lowercase	(  lowerCAmelCase__  ,lowerCAmelCase__	):
			return numpy.exp(lowerCAmelCase__	) + c_parameter






def    lowercase	(  lowerCAmelCase__  ,lowerCAmelCase__	):
			return z_values * z_values + c_parameter






def    lowercase	(  lowerCAmelCase__  ,lowerCAmelCase__	):
			lowerCamelCase_ 		=     numpy.linspace(-window_size  ,lowerCAmelCase__  ,lowerCAmelCase__	)
			lowerCamelCase_ 		=     x.reshape((nb_pixels, 1)	)
			lowerCamelCase_ 		=     numpy.linspace(-window_size  ,lowerCAmelCase__  ,lowerCAmelCase__	)
			lowerCamelCase_ 		=     y.reshape((1, nb_pixels)	)
			return x + 1.0J * y






def    lowercase	(  lowerCAmelCase__  ,lowerCAmelCase__  ,lowerCAmelCase__  ,lowerCAmelCase__  ,lowerCAmelCase__ = None  ,):
			lowerCamelCase_ 		=     z_a.astype('''complex64'''	)
			for _ in range(lowerCAmelCase__	):
						lowerCamelCase_ 		=     eval_function(lowerCAmelCase__  ,lowerCAmelCase__	)
						if infinity is not None:
									numpy.nan_to_num(lowerCAmelCase__  ,copy=lowerCAmelCase__  ,nan=lowerCAmelCase__	)
									lowerCamelCase_ 		=     infinity
			return z_n






def    lowercase	(  lowerCAmelCase__  ,lowerCAmelCase__  ,lowerCAmelCase__  ,lowerCAmelCase__  ,):
			lowerCamelCase_ 		=     (abs(lowerCAmelCase__	)).transpose()
			lowerCamelCase_ 		=     abs_z_final[::-1, :]
			pyplot.matshow(abs_z_final < escape_radius	)
			pyplot.title(f"Julia set of ${function_label}$, $c={function_params}$"	)
			pyplot.show()






def    lowercase	(  ):
			warnings.filterwarnings(
			    '''ignore'''  ,category=lowerCAmelCase__  ,message='''overflow encountered in multiply'''	)
			warnings.filterwarnings(
			    '''ignore'''  ,category=lowerCAmelCase__  ,message='''invalid value encountered in multiply'''  ,)
			warnings.filterwarnings(
			    '''ignore'''  ,category=lowerCAmelCase__  ,message='''overflow encountered in absolute'''	)
			warnings.filterwarnings(
			    '''ignore'''  ,category=lowerCAmelCase__  ,message='''overflow encountered in exp'''	)


if __name__ == "__main__":
						A_						       =				prepare_grid(window_size, nb_pixels)

						ignore_overflow_warnings()  # See file header for explanations

						A_						       =				24
						A_						       =				2 * abs(c_cauliflower) + 1
						A_						       =				iterate_function(
						    eval_quadratic_polynomial,
						    c_cauliflower,
						    nb_iterations,
						    z_a,
						    infinity=1.1 * escape_radius,
						)
						show_results("""z^2+c""", c_cauliflower, escape_radius, z_final)

						A_						       =				64
						A_						       =				2 * abs(c_polynomial_a) + 1
						A_						       =				iterate_function(
						    eval_quadratic_polynomial,
						    c_polynomial_a,
						    nb_iterations,
						    z_a,
						    infinity=1.1 * escape_radius,
						)
						show_results("""z^2+c""", c_polynomial_a, escape_radius, z_final)

						A_						       =				161
						A_						       =				2 * abs(c_polynomial_a) + 1
						A_						       =				iterate_function(
						    eval_quadratic_polynomial,
						    c_polynomial_a,
						    nb_iterations,
						    z_a,
						    infinity=1.1 * escape_radius,
						)
						show_results("""z^2+c""", c_polynomial_a, escape_radius, z_final)

						A_						       =				12
						A_						       =				10000.0
						A_						       =				iterate_function(
						    eval_exponential,
						    c_exponential,
						    nb_iterations,
						    z_a + 2,
						    infinity=1.0e10,
						)
						show_results("""e^z+c""", c_exponential, escape_radius, z_final)



