


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


A :	int												=     logging.getLogger(__name__)



@dataclass
class 							A					:
					'''simple docstring'''






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






def 				UpperCamelCase      (			__magic_name__  :							ModelArguments					,					__magic_name__  :							TrainingArguments  )     ->						Dict:
		"""simple docstring"""




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



@dataclass
class 							A					:
					'''simple docstring'''






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






@dataclass
class 							A					:
					'''simple docstring'''






					A__    =				False
					A__    =				None
					A__    =				'''|'''
					A__    =				field(default_factory=UpperCAmelCase__							)
					A__    =				field(default_factory=UpperCAmelCase__							)
					A__    =				None

					@classmethod
					def 						lowerCamelCase__  (cls					:		Any   ,      _UpperCAmelCase					:		str	)		->     Union[str, Any]:




							"""simple docstring"""


							if name == "librispeech":
									return cls()
							if name == "timit":
									return cls(
									    do_lower_case=_UpperCAmelCase   ,      translation_table=str.maketrans({"""-""": """ """}	)   ,      )
							if name == "buckwalter":
									lowercase__      =							{
									    """-""": """ """,  # 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 						lowerCamelCase__  (self					:		List[str]   ,      _UpperCAmelCase					:		str	)		->     str:




							"""simple docstring"""


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


					def 						lowerCamelCase__  (self					:		Union[str, Any]   ,      _UpperCAmelCase					:		ModelArguments	)		->     WavaVecaProcessor:




							"""simple docstring"""


							lowercase__      =							WavaVecaFeatureExtractor.from_pretrained(
							    model_args.model_name_or_path   ,      cache_dir=model_args.cache_dir	)
							if self.vocab_file:
									lowercase__      =							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:
									lowercase__      =							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 							A					:
					'''simple docstring'''






					A__    =				42
					A__    =				True
					A__    =				None
					A__    =				None
					A__    =				None
					A__    =				None

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




							"""simple docstring"""


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

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

							lowercase__      =							labels

							return batch






class 							A					( UpperCAmelCase__							):
					'''simple docstring'''






					def 						lowerCamelCase__  (self					:		Any   ,      _UpperCAmelCase					:		nn.Module   ,      _UpperCAmelCase					:		Dict[str, Union[torch.Tensor, Any]]	)		->     torch.Tensor:




							"""simple docstring"""


							model.train()
							lowercase__      =							self._prepare_inputs(_UpperCAmelCase	)

							if self.use_amp:
									with autocast():
											lowercase__      =							self.compute_loss(_UpperCAmelCase   ,      _UpperCAmelCase	)
							else:
									lowercase__      =							self.compute_loss(_UpperCAmelCase   ,      _UpperCAmelCase	)

							if self.args.n_gpu > 1:
									if model.module.config.ctc_loss_reduction == "mean":
											lowercase__      =							loss.mean()
									elif model.module.config.ctc_loss_reduction == "sum":
											lowercase__      =							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:
									lowercase__      =							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 				UpperCamelCase      (			)     ->						List[Any]:
		"""simple docstring"""




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

		lowercase__    ,			lowercase__    ,			lowercase__      =							parser.parse_args_into_dataclasses()
		configure_logger(__magic_name__					,					__magic_name__  )

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

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

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

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

		lowercase__      =							train_dataset.map(__magic_name__					,					remove_columns=[data_args.speech_file_column]  )
		lowercase__      =							val_dataset.map(__magic_name__					,					remove_columns=[data_args.speech_file_column]  )

		if data_args.max_duration_in_seconds is not None:

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

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

		logger.warning(f'''Updated {len(__magic_name__  )} 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}"'''  )
		lowercase__      =							None

		def prepare_dataset(__magic_name__  :							Union[str, Any]  ):
				# 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}.'''

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

		lowercase__      =							train_dataset.map(
		    __magic_name__					,					batch_size=training_args.per_device_train_batch_size					,					batched=__magic_name__					,					num_proc=data_args.preprocessing_num_workers					,					)
		lowercase__      =							val_dataset.map(
		    __magic_name__					,					batch_size=training_args.per_device_train_batch_size					,					batched=__magic_name__					,					num_proc=data_args.preprocessing_num_workers					,					)

		lowercase__      =							DataCollatorCTCWithPadding(processor=__magic_name__					,					padding=__magic_name__  )

		def compute_metrics(__magic_name__  :							List[str]  ):
				lowercase__      =							pred.predictions
				lowercase__      =							np.argmax(__magic_name__					,					axis=-1  )

				lowercase__      =							processor.tokenizer.pad_token_id

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

				lowercase__      =							wer_metric.compute(predictions=__magic_name__					,					references=__magic_name__  )

				return {"wer": wer}

		if model_args.freeze_feature_extractor:
				model.freeze_feature_extractor()

		lowercase__      =							CTCTrainer(
		    model=__magic_name__					,					data_collator=__magic_name__					,					args=__magic_name__					,					compute_metrics=__magic_name__					,					train_dataset=__magic_name__					,					eval_dataset=__magic_name__					,					tokenizer=processor.feature_extractor					,					)

		trainer.train()


if __name__ == "__main__":
	main()





import os
import sys

from . import rsa_key_generator as rkg

A :	List[str]												=     1_2_8
A :	Optional[Any]												=     2_5_6






def 				UpperCamelCase      (			__magic_name__  :							str					,					__magic_name__  :							int = DEFAULT_BLOCK_SIZE  )     ->						list[int]:
		"""simple docstring"""




		lowercase__      =	message.encode("""ascii"""  )

		lowercase__      =	[]
		for block_start in range(0					,					len(__magic_name__  )					,					__magic_name__  ):
				lowercase__      =	0
				for i in range(__magic_name__					,					min(block_start + block_size					,					len(__magic_name__  )  )  ):
						block_int += message_bytes[i] * (BYTE_SIZE ** (i % block_size))
				block_ints.append(__magic_name__  )
		return block_ints






def 				UpperCamelCase      (			__magic_name__  :							list[int]					,					__magic_name__  :							int					,					__magic_name__  :							int = DEFAULT_BLOCK_SIZE  )     ->						str:
		"""simple docstring"""




		lowercase__      =	[]
		for block_int in block_ints:
				lowercase__      =	[]
				for i in range(block_size - 1					,					-1					,					-1  ):
						if len(__magic_name__  ) + i < message_length:
								lowercase__      =	block_int // (BYTE_SIZE**i)
								lowercase__      =	block_int % (BYTE_SIZE**i)
								block_message.insert(0					,					chr(__magic_name__  )  )
				message.extend(__magic_name__  )
		return "".join(__magic_name__  )






def 				UpperCamelCase      (			__magic_name__  :							str					,					__magic_name__  :							tuple[int, int]					,					__magic_name__  :							int = DEFAULT_BLOCK_SIZE  )     ->						list[int]:
		"""simple docstring"""




		lowercase__      =	[]
		lowercase__    ,			lowercase__      =	key

		for block in get_blocks_from_text(__magic_name__					,					__magic_name__  ):
				encrypted_blocks.append(pow(__magic_name__					,					__magic_name__					,					__magic_name__  )  )
		return encrypted_blocks






def 				UpperCamelCase      (			__magic_name__  :							list[int]					,					__magic_name__  :							int					,					__magic_name__  :							tuple[int, int]					,					__magic_name__  :							int = DEFAULT_BLOCK_SIZE					,					)     ->						str:
		"""simple docstring"""




		lowercase__      =	[]
		lowercase__    ,			lowercase__      =	key
		for block in encrypted_blocks:
				decrypted_blocks.append(pow(__magic_name__					,					__magic_name__					,					__magic_name__  )  )
		return get_text_from_blocks(__magic_name__					,					__magic_name__					,					__magic_name__  )






def 				UpperCamelCase      (			__magic_name__  :							str  )     ->						tuple[int, int, int]:
		"""simple docstring"""




		with open(__magic_name__  ) as fo:
				lowercase__      =	fo.read()
		lowercase__    ,			lowercase__    ,			lowercase__      =	content.split(""","""  )
		return (int(__magic_name__  ), int(__magic_name__  ), int(__magic_name__  ))






def 				UpperCamelCase      (			__magic_name__  :							str					,					__magic_name__  :							str					,					__magic_name__  :							str					,					__magic_name__  :							int = DEFAULT_BLOCK_SIZE					,					)     ->						str:
		"""simple docstring"""




		lowercase__    ,			lowercase__    ,			lowercase__      =	read_key_file(__magic_name__  )
		if key_size < block_size * 8:
				sys.exit(
				    """ERROR: Block size is {} bits and key size is {} bits. The RSA cipher """
				    """requires the block size to be equal to or greater than the key size. """
				    """Either decrease the block size or use different keys.""".format(
				        block_size * 8					,					__magic_name__  )  )

		lowercase__      =	[str(__magic_name__  ) for i in encrypt_message(__magic_name__					,					(n, e)					,					__magic_name__  )]

		lowercase__      =	""",""".join(__magic_name__  )
		lowercase__      =	f'''{len(__magic_name__  )}_{block_size}_{encrypted_content}'''
		with open(__magic_name__					,					"""w"""  ) as fo:
				fo.write(__magic_name__  )
		return encrypted_content






def 				UpperCamelCase      (			__magic_name__  :							str					,					__magic_name__  :							str  )     ->						str:
		"""simple docstring"""




		lowercase__    ,			lowercase__    ,			lowercase__      =	read_key_file(__magic_name__  )
		with open(__magic_name__  ) as fo:
				lowercase__      =	fo.read()
		lowercase__    ,			lowercase__    ,			lowercase__      =	content.split("""_"""  )
		lowercase__      =	int(__magic_name__  )
		lowercase__      =	int(__magic_name__  )

		if key_size < block_size * 8:
				sys.exit(
				    """ERROR: Block size is {} bits and key size is {} bits. The RSA cipher """
				    """requires the block size to be equal to or greater than the key size. """
				    """Did you specify the correct key file and encrypted file?""".format(
				        block_size * 8					,					__magic_name__  )  )

		lowercase__      =	[]
		for block in encrypted_message.split(""","""  ):
				encrypted_blocks.append(int(__magic_name__  )  )

		return decrypt_message(__magic_name__					,					__magic_name__					,					(n, d)					,					__magic_name__  )






def 				UpperCamelCase      (			)     ->						None:
		"""simple docstring"""




		lowercase__      =	"""encrypted_file.txt"""
		lowercase__      =	input(R"""Encrypt\Decrypt [e\d]: """  )

		if response.lower().startswith("""e"""  ):
				lowercase__      =	"""encrypt"""
		elif response.lower().startswith("""d"""  ):
				lowercase__      =	"""decrypt"""

		if mode == "encrypt":
				if not os.path.exists("""rsa_pubkey.txt"""  ):
						rkg.make_key_files("""rsa"""					,					1024  )

				lowercase__      =	input("""\nEnter message: """  )
				lowercase__      =	"""rsa_pubkey.txt"""
				print(f'''Encrypting and writing to {filename}...'''  )
				lowercase__      =	encrypt_and_write_to_file(__magic_name__					,					__magic_name__					,					__magic_name__  )

				print("""\nEncrypted text:"""  )
				print(__magic_name__  )

		elif mode == "decrypt":
				lowercase__      =	"""rsa_privkey.txt"""
				print(f'''Reading from {filename} and decrypting...'''  )
				lowercase__      =	read_from_file_and_decrypt(__magic_name__					,					__magic_name__  )
				print("""writing decryption to rsa_decryption.txt..."""  )
				with open("""rsa_decryption.txt"""					,					"""w"""  ) as dec:
						dec.write(__magic_name__  )

				print("""\nDecryption:"""  )
				print(__magic_name__  )


if __name__ == "__main__":
	main()

