

import math





class 			snake_case_     :







			'''simple docstring'''

			def __init__(  self				:       Optional[int]							,     _UpperCamelCase				:       int							,     _UpperCamelCase				:       int							,     _UpperCamelCase				:       int							,     _UpperCamelCase				:       Tuple							)   ->Union[str, Any]:
									snake_case_     =			x
									snake_case_     =			y
									snake_case_     =			step_size
									snake_case_     =			function_to_optimize







			def        snake_case__(  self				:       List[str]							)   ->int:
									return self.function(self.x							,     self.y							)







			def        snake_case__(  self				:       int							)   ->int:
									snake_case_     =			self.step_size
									return [
									    SearchProblem(_UpperCamelCase							,     _UpperCamelCase							,     _UpperCamelCase							,     self.function							)
									    for x, y in (
									        (self.x - step_size, self.y - step_size),
									        (self.x - step_size, self.y),
									        (self.x - step_size, self.y + step_size),
									        (self.x, self.y - step_size),
									        (self.x, self.y + step_size),
									        (self.x + step_size, self.y - step_size),
									        (self.x + step_size, self.y),
									        (self.x + step_size, self.y + step_size),
									    )
									]







			def __hash__(  self				:       Optional[int]							)   ->str:
									return hash(str(self							)							)







			def __eq__(  self				:       List[Any]							,     _UpperCamelCase				:       int							)   ->Union[str, Any]:
									if isinstance(_UpperCamelCase							,     _UpperCamelCase							):
															return hash(str(self							)							) == hash(str(_UpperCamelCase							)							)
									return False







			def __str__(  self				:       List[str]							)   ->Union[str, Any]:
									return f'''x: {self.x} y: {self.y}'''






def 						__SCREAMING_SNAKE_CASE      (SCREAMING_SNAKE_CASE__						,	SCREAMING_SNAKE_CASE__ = True						,	SCREAMING_SNAKE_CASE__ = math.inf						,	SCREAMING_SNAKE_CASE__ = -math.inf						,	SCREAMING_SNAKE_CASE__ = math.inf						,	SCREAMING_SNAKE_CASE__ = -math.inf						,	SCREAMING_SNAKE_CASE__ = False						,	SCREAMING_SNAKE_CASE__ = 10000						,	)     ->   int:
						snake_case_     =			search_prob
						snake_case_     =			[]  # list to store the current score at each iteration
						snake_case_     =			0
						snake_case_     =			False
						snake_case_     =			set()
						while not solution_found and iterations < max_iter:
												visited.add(SCREAMING_SNAKE_CASE__ )
												iterations += 1
												snake_case_     =			current_state.score()
												scores.append(SCREAMING_SNAKE_CASE__ )
												snake_case_     =			current_state.get_neighbors()
												snake_case_     =			-math.inf
												snake_case_     =			math.inf
												snake_case_     =			None  # to hold the next best neighbor
												for neighbor in neighbors:
																		if neighbor in visited:
																								continue  # do not want to visit the same state again
																		if (
																		    neighbor.x > max_x
																		    or neighbor.x < min_x
																		    or neighbor.y > max_y
																		    or neighbor.y < min_y
																		):
																								continue  # neighbor outside our bounds
																		snake_case_     =			neighbor.score() - current_score
																		if find_max:  # finding max
																								# going to direction with greatest ascent
																								if change > max_change and change > 0:
																														snake_case_     =			change
																														snake_case_     =			neighbor
																		else:  # finding min
																								# to direction with greatest descent
																								if change < min_change and change < 0:
																														snake_case_     =			change
																														snake_case_     =			neighbor
												if next_state is not None:
																		# we found at least one neighbor which improved the current state
																		snake_case_     =			next_state
												else:
																		# since we have no neighbor that improves the solution we stop the search
																		snake_case_     =			True

						if visualization:
												from matplotlib import pyplot as plt

												plt.plot(range(SCREAMING_SNAKE_CASE__ )						,	SCREAMING_SNAKE_CASE__ )
												plt.xlabel('''Iterations''' )
												plt.ylabel('''Function values''' )
												plt.show()

						return current_state


if __name__ == "__main__":
					import doctest

					doctest.testmod()


					def 						__SCREAMING_SNAKE_CASE      (SCREAMING_SNAKE_CASE__						,	SCREAMING_SNAKE_CASE__ )     ->   Optional[int]:
											return (x**2) + (y**2)

					# starting the problem with initial coordinates (3, 4)
					lowerCAmelCase_ 			=			SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa)
					lowerCAmelCase_ 			=			hill_climbing(prob, find_max=False)
					print(
					    '''The minimum score for f(x, y) = x^2 + y^2 found via hill climbing: '''
					    f"""{local_min.score()}"""
					)

					# starting the problem with initial coordinates (12, 47)
					lowerCAmelCase_ 			=			SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa)
					lowerCAmelCase_ 			=			hill_climbing(
					    prob, find_max=False, max_x=1_00, min_x=5, max_y=50, min_y=-5, visualization=True
					)
					print(
					    '''The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 '''
					    f"""and 50 > y > - 5 found via hill climbing: {local_min.score()}"""
					)


					def 						__SCREAMING_SNAKE_CASE      (SCREAMING_SNAKE_CASE__						,	SCREAMING_SNAKE_CASE__ )     ->   Optional[int]:
											return (3 * x**2) - (6 * y)

					lowerCAmelCase_ 			=			SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa)
					lowerCAmelCase_ 			=			hill_climbing(prob, find_max=True)
					print(
					    '''The maximum score for f(x, y) = x^2 + y^2 found via hill climbing: '''
					    f"""{local_min.score()}"""
					)


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


lowerCAmelCase_ 			=			logging.getLogger(__name__)





@dataclass
class 			snake_case_     :







			'''simple docstring'''

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






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





@dataclass
class 			snake_case_     :







			'''simple docstring'''

			SCREAMING_SNAKE_CASE  :     str		    =       field(
			    default=__A			, metadata={"help": "The name of the dataset to use (via the datasets library)."}      )
			SCREAMING_SNAKE_CASE  :     Optional[str]		    =       field(
			    default=__A			, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}      )
			SCREAMING_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'"
			    }			, )
			SCREAMING_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'"
			        )
			    }			, )
			SCREAMING_SNAKE_CASE  :     Optional[str]		    =       field(
			    default="text"			, metadata={"help": "Column in the dataset that contains label (target text). Defaults to 'text'"}			, )
			SCREAMING_SNAKE_CASE  :     Optional[str]		    =       field(
			    default="file"			, metadata={"help": "Column in the dataset that contains speech file path. Defaults to 'file'"}			, )
			SCREAMING_SNAKE_CASE  :     Optional[bool]		    =       field(
			    default=__A			, metadata={"help": "Resample loaded audio to target feature extractor's sampling rate or not."}			, )
			SCREAMING_SNAKE_CASE  :     Optional[float]		    =       field(
			    default=__A			, metadata={"help": "Filters out examples longer than specified. Defaults to no filtering."}			, )
			SCREAMING_SNAKE_CASE  :     Optional[str]		    =       field(
			    default="librispeech"			, metadata={
			        "help": (
			            "Orthography used for normalization and tokenization: 'librispeech' (default), 'timit', or"
			            " 'buckwalter'."
			        )
			    }			, )
			SCREAMING_SNAKE_CASE  :     bool		    =       field(
			    default=__A			, metadata={"help": "Overwrite the cached preprocessed datasets or not."}      )
			SCREAMING_SNAKE_CASE  :     Optional[int]		    =       field(
			    default=__A			, metadata={"help": "The number of processes to use for the preprocessing."}			, )






@dataclass
class 			snake_case_     :







			'''simple docstring'''

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







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







			'''simple docstring'''

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







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

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

									snake_case_     =			labels

									return batch






class 			snake_case_     (	__A      ):







			'''simple docstring'''

			def        snake_case__(  self				:       Tuple							,     _UpperCamelCase				:       nn.Module							,     _UpperCamelCase				:       Dict[str, Union[torch.Tensor, Any]]							)   ->torch.Tensor:
									model.train()
									snake_case_     =			self._prepare_inputs(_UpperCamelCase							)

									if self.use_amp:
															with autocast():
																					snake_case_     =			self.compute_loss(_UpperCamelCase							,     _UpperCamelCase							)
									else:
															snake_case_     =			self.compute_loss(_UpperCamelCase							,     _UpperCamelCase							)

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

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

						snake_case_,					snake_case_,					snake_case_     =			parser.parse_args_into_dataclasses()
						configure_logger(SCREAMING_SNAKE_CASE__						,	SCREAMING_SNAKE_CASE__ )

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

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

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

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

						snake_case_     =			train_dataset.map(SCREAMING_SNAKE_CASE__						,	remove_columns=[data_args.speech_file_column] )
						snake_case_     =			val_dataset.map(SCREAMING_SNAKE_CASE__						,	remove_columns=[data_args.speech_file_column] )

						if data_args.max_duration_in_seconds is not None:

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

												snake_case_     =			len(SCREAMING_SNAKE_CASE__ )
												snake_case_     =			len(SCREAMING_SNAKE_CASE__ )
												snake_case_     =			train_dataset.filter(SCREAMING_SNAKE_CASE__						,	remove_columns=['''duration_in_seconds'''] )
												snake_case_     =			val_dataset.filter(SCREAMING_SNAKE_CASE__						,	remove_columns=['''duration_in_seconds'''] )
												if len(SCREAMING_SNAKE_CASE__ ) > old_train_size:
																		logger.warning(
																		    F'''Filtered out {len(SCREAMING_SNAKE_CASE__ ) - old_train_size} train example(s) longer than'''
																		    F''' {data_args.max_duration_in_seconds} second(s).''' )
												if len(SCREAMING_SNAKE_CASE__ ) > old_val_size:
																		logger.warning(
																		    F'''Filtered out {len(SCREAMING_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(SCREAMING_SNAKE_CASE__ )} train and {len(SCREAMING_SNAKE_CASE__ )} validation.''' )

						logger.warning(F'''Updated {len(SCREAMING_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}"''' )
						snake_case_     =			None

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

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

						snake_case_     =			train_dataset.map(
						    SCREAMING_SNAKE_CASE__						,	batch_size=training_args.per_device_train_batch_size						,	batched=SCREAMING_SNAKE_CASE__						,	num_proc=data_args.preprocessing_num_workers						,	)
						snake_case_     =			val_dataset.map(
						    SCREAMING_SNAKE_CASE__						,	batch_size=training_args.per_device_train_batch_size						,	batched=SCREAMING_SNAKE_CASE__						,	num_proc=data_args.preprocessing_num_workers						,	)

						snake_case_     =			DataCollatorCTCWithPadding(processor=SCREAMING_SNAKE_CASE__						,	padding=SCREAMING_SNAKE_CASE__ )

						def compute_metrics(SCREAMING_SNAKE_CASE__ ):
												snake_case_     =			pred.predictions
												snake_case_     =			np.argmax(SCREAMING_SNAKE_CASE__						,	axis=-1 )

												snake_case_     =			processor.tokenizer.pad_token_id

												snake_case_     =			processor.batch_decode(SCREAMING_SNAKE_CASE__ )
												# we do not want to group tokens when computing the metrics
												snake_case_     =			processor.batch_decode(pred.label_ids						,	group_tokens=SCREAMING_SNAKE_CASE__ )
												if logger.isEnabledFor(logging.DEBUG ):
																		for reference, predicted in zip(SCREAMING_SNAKE_CASE__						,	SCREAMING_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(SCREAMING_SNAKE_CASE__ )}"''' )
																														logger.debug(F'''predicted (untransliterated): "{orthography.untransliterator(SCREAMING_SNAKE_CASE__ )}"''' )

												snake_case_     =			wer_metric.compute(predictions=SCREAMING_SNAKE_CASE__						,	references=SCREAMING_SNAKE_CASE__ )

												return {"wer": wer}

						if model_args.freeze_feature_extractor:
												model.freeze_feature_extractor()

						snake_case_     =			CTCTrainer(
						    model=SCREAMING_SNAKE_CASE__						,	data_collator=SCREAMING_SNAKE_CASE__						,	args=SCREAMING_SNAKE_CASE__						,	compute_metrics=SCREAMING_SNAKE_CASE__						,	train_dataset=SCREAMING_SNAKE_CASE__						,	eval_dataset=SCREAMING_SNAKE_CASE__						,	tokenizer=processor.feature_extractor						,	)

						trainer.train()


if __name__ == "__main__":
					main()