



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__	:  Tuple 		=True
			from torch.cuda.amp import autocast


lowerCAmelCase__	:  Tuple 		=logging.getLogger(__name__)

@dataclass
class      UpperCAmelCase_						:

						'''simple docstring'''




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







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

@dataclass
class      UpperCAmelCase_						:

						'''simple docstring'''




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







@dataclass
class      UpperCAmelCase_						:

						'''simple docstring'''




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






						@classmethod
						def  _A			(					cls   ,							_A	):







													'''simple docstring'''

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







													'''simple docstring'''

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






						def  _A			(					self   ,							_A	):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE								=      WavaVecaFeatureExtractor.from_pretrained(
													    model_args.model_name_or_path   ,							cache_dir=model_args.cache_dir	)
													if self.vocab_file:
																				__SCREAMING_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:
																				__SCREAMING_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(_A   ,							_A	)







@dataclass
class      UpperCAmelCase_						:

						'''simple docstring'''




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






						def __call__(					self   ,							_A	):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE								=      [{'input_values': feature['input_values']} for feature in features]
													__SCREAMING_SNAKE_CASE								=      [{'input_ids': feature['labels']} for feature in features]

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

													__SCREAMING_SNAKE_CASE								=      labels

													return batch







class      UpperCAmelCase_						(     UpperCamelCase_ ):

						'''simple docstring'''




						def  _A			(					self   ,							_A   ,							_A	):







													'''simple docstring'''

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

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

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

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

							__SCREAMING_SNAKE_CASE							, __SCREAMING_SNAKE_CASE							, __SCREAMING_SNAKE_CASE								=      parser.parse_args_into_dataclasses()
							configure_logger(a__							,     a__     )

							__SCREAMING_SNAKE_CASE								=      Orthography.from_name(data_args.orthography.lower()     )
							__SCREAMING_SNAKE_CASE								=      orthography.create_processor(a__     )
							__SCREAMING_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     )							,     )

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

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

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

							__SCREAMING_SNAKE_CASE								=      train_dataset.map(a__							,     remove_columns=[data_args.speech_file_column]     )
							__SCREAMING_SNAKE_CASE								=      val_dataset.map(a__							,     remove_columns=[data_args.speech_file_column]     )

							if data_args.max_duration_in_seconds is not None:

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

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

							logger.warning(f"""Updated {len(a__     )} 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}\""""     )
							__SCREAMING_SNAKE_CASE								=      None

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

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

							__SCREAMING_SNAKE_CASE								=      train_dataset.map(
							    a__							,     batch_size=training_args.per_device_train_batch_size							,     batched=a__							,     num_proc=data_args.preprocessing_num_workers							,     )
							__SCREAMING_SNAKE_CASE								=      val_dataset.map(
							    a__							,     batch_size=training_args.per_device_train_batch_size							,     batched=a__							,     num_proc=data_args.preprocessing_num_workers							,     )

							__SCREAMING_SNAKE_CASE								=      DataCollatorCTCWithPadding(processor=a__							,     padding=a__     )

							def compute_metrics(a__     ):
														__SCREAMING_SNAKE_CASE								=      pred.predictions
														__SCREAMING_SNAKE_CASE								=      np.argmax(a__							,     axis=-1     )

														__SCREAMING_SNAKE_CASE								=      processor.tokenizer.pad_token_id

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

														__SCREAMING_SNAKE_CASE								=      wer_metric.compute(predictions=a__							,     references=a__     )

														return {"wer": wer}

							if model_args.freeze_feature_extractor:
														model.freeze_feature_extractor()

							__SCREAMING_SNAKE_CASE								=      CTCTrainer(
							    model=a__							,     data_collator=a__							,     args=a__							,     compute_metrics=a__							,     train_dataset=a__							,     eval_dataset=a__							,     tokenizer=processor.feature_extractor							,     )

							trainer.train()


if __name__ == "__main__":
			main()











def 			__lowercase     (				a__     )       ->				list:
							__SCREAMING_SNAKE_CASE								=      1.3
							__SCREAMING_SNAKE_CASE								=      len(a__     )
							__SCREAMING_SNAKE_CASE								=      False

							while not completed:
														# Update the gap value for a next comb
														__SCREAMING_SNAKE_CASE								=      int(gap / shrink_factor     )
														if gap <= 1:
																					__SCREAMING_SNAKE_CASE								=      True

														__SCREAMING_SNAKE_CASE								=      0
														while index + gap < len(a__     ):
																					if data[index] > data[index + gap]:
																												# Swap values
																												__SCREAMING_SNAKE_CASE							, __SCREAMING_SNAKE_CASE								=      data[index + gap], data[index]
																												__SCREAMING_SNAKE_CASE								=      False
																					index += 1

							return data


if __name__ == "__main__":
			import doctest

			doctest.testmod()

			lowerCAmelCase__	:  int 		=input('''Enter numbers separated by a comma:\n''').strip()
			lowerCAmelCase__	:  Dict 		=[int(item) for item in user_input.split(''',''')]
			print(comb_sort(unsorted))






