
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      SCREAMING_SNAKE_CASE__  :





	'''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  a_	( __lowercase     :			ModelArguments ,      __lowercase     :			TrainingArguments				)				->						Dict:
			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(__lowercase				)




@dataclass
class      SCREAMING_SNAKE_CASE__  :





	'''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      SCREAMING_SNAKE_CASE__  :





	'''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			:					Any    ,						lowercase			:					str			):


				'''simple docstring'''


				if name == "librispeech":
							return cls()
				if name == "timit":
							return cls(
							    do_lower_case=lowercase    ,						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(lowercase			).parent.joinpath('vocab/buckwalter.json'			)    ,						word_delimiter_token='/'    ,						translation_table=str.maketrans(lowercase			)    ,						words_to_remove={'sil'}    ,						untransliterator=arabic.buckwalter.untransliterate    ,						)
				raise ValueError(f'''Unsupported orthography: \'{name}\'.'''			)



	def 				A							(						self			:					Dict    ,						lowercase			:					str			):


				'''simple docstring'''


				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 				A							(						self			:					Tuple    ,						lowercase			:					ModelArguments			):


				'''simple docstring'''


				_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(lowercase    ,						lowercase			)




@dataclass
class      SCREAMING_SNAKE_CASE__  :





	'''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			:					str    ,						lowercase			:					List[Dict[str, Union[List[int], torch.Tensor]]]			):


				'''simple docstring'''


				_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(
				    lowercase    ,						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=lowercase    ,						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			)    ,						-100			)

				_snake_case						=    labels

				return batch




class      SCREAMING_SNAKE_CASE__  (			UpperCAmelCase      ):





	'''simple docstring'''



	def 				A							(						self			:					Union[str, Any]    ,						lowercase			:					nn.Module    ,						lowercase			:					Dict[str, Union[torch.Tensor, Any]]			):


				'''simple docstring'''


				model.train()
				_snake_case						=    self._prepare_inputs(lowercase			)

				if self.use_amp:
							with autocast():
										_snake_case						=    self.compute_loss(lowercase    ,						lowercase			)
				else:
							_snake_case						=    self.compute_loss(lowercase    ,						lowercase			)

				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(lowercase			).backward()
				elif self.use_apex:
							with amp.scale_loss(lowercase    ,						self.optimizer			) as scaled_loss:
										scaled_loss.backward()
				elif self.deepspeed:
							self.deepspeed.backward(lowercase			)
				else:
							loss.backward()

				return loss.detach()






def  a_	( )				->						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.

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

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

			_snake_case						=    Orthography.from_name(data_args.orthography.lower()				)
			_snake_case						=    orthography.create_processor(__lowercase				)
			_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(__lowercase				) == 1				)
			_snake_case						=    re.compile(  # remove characters not in vocabulary
			    rf'''[^\s{re.escape(__lowercase				)}]''' ,      flags=re.IGNORECASE if processor.tokenizer.do_lower_case else 0 ,      )
			_snake_case						=    []

			def prepare_example(__lowercase     :			List[str]				):  # TODO(elgeish) make use of multiprocessing?
						_snake_case			,      _snake_case						=    librosa.load(example[data_args.speech_file_column] ,      sr=__lowercase				)
						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('' ,      __lowercase				)
						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(__lowercase ,      remove_columns=[data_args.speech_file_column]				)
			_snake_case						=    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     :			Dict				):
									return example["duration_in_seconds"] <= data_args.max_duration_in_seconds

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

			def prepare_dataset(__lowercase     :			Tuple				):
						# 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(__lowercase				)
						return batch

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

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

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

						_snake_case						=    processor.tokenizer.pad_token_id

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

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

						return {"wer": wer}

			if model_args.freeze_feature_extractor:
						model.freeze_feature_extractor()

			_snake_case						=    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 random
import sys

_lowerCamelCase :       Tuple     					=    '''ABCDEFGHIJKLMNOPQRSTUVWXYZ'''






def  a_	( )				->						None:
			_snake_case						=    input('Enter message: '				)
			_snake_case						=    'LFWOAYUISVKMNXPBDCRJTQEGHZ'
			_snake_case						=    input('Encrypt/Decrypt [e/d]: '				)

			check_valid_key(__lowercase				)

			if resp.lower().startswith('e'				):
						_snake_case						=    'encrypt'
						_snake_case						=    encrypt_message(__lowercase ,      __lowercase				)
			elif resp.lower().startswith('d'				):
						_snake_case						=    'decrypt'
						_snake_case						=    decrypt_message(__lowercase ,      __lowercase				)

			print(f'''\n{mode.title()}ion: \n{translated}'''				)






def  a_	( __lowercase     :			str				)				->						None:
			_snake_case						=    list(__lowercase				)
			_snake_case						=    list(__lowercase				)
			key_list.sort()
			letters_list.sort()

			if key_list != letters_list:
						sys.exit('Error in the key or symbol set.'				)






def  a_	( __lowercase     :			str ,      __lowercase     :			str				)				->						str:
			return translate_message(__lowercase ,      __lowercase ,      'encrypt'				)






def  a_	( __lowercase     :			str ,      __lowercase     :			str				)				->						str:
			return translate_message(__lowercase ,      __lowercase ,      'decrypt'				)






def  a_	( __lowercase     :			str ,      __lowercase     :			str ,      __lowercase     :			str				)				->						str:
			_snake_case						=    ''
			_snake_case						=    LETTERS
			_snake_case						=    key

			if mode == "decrypt":
						_snake_case			,      _snake_case						=    chars_b, chars_a

			for symbol in message:
						if symbol.upper() in chars_a:
									_snake_case						=    chars_a.find(symbol.upper()				)
									if symbol.isupper():
												translated += chars_b[sym_index].upper()
									else:
												translated += chars_b[sym_index].lower()
						else:
									translated += symbol

			return translated






def  a_	( )				->						str:
			_snake_case						=    list(__lowercase				)
			random.shuffle(__lowercase				)
			return "".join(__lowercase				)


if __name__ == "__main__":
			main()