

def       __a       (   SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE      )      ->     str:






    '''simple docstring'''
    if not isinstance(SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE      ):
        raise TypeError('''plaintext must be a string'''      )
    if not isinstance(SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE      ):
        raise TypeError('''key must be a string'''      )

    if not plaintext:
        raise ValueError('''plaintext is empty'''      )
    if not key:
        raise ValueError('''key is empty'''      )

    key += plaintext
    __UpperCAmelCase									=			plaintext.lower()
    __UpperCAmelCase									=			key.lower()
    __UpperCAmelCase									=			0
    __UpperCAmelCase									=			0
    __UpperCAmelCase									=			''''''
    while plaintext_iterator < len(SCREAMING_SNAKE_CASE      ):
        if (
            ord(plaintext[plaintext_iterator]      ) < 9_7
            or ord(plaintext[plaintext_iterator]      ) > 1_2_2
        ):
            ciphertext += plaintext[plaintext_iterator]
            plaintext_iterator += 1
        elif ord(key[key_iterator]      ) < 9_7 or ord(key[key_iterator]      ) > 1_2_2:
            key_iterator += 1
        else:
            ciphertext += chr(
                (
                    (ord(plaintext[plaintext_iterator]      ) - 9_7 + ord(key[key_iterator]      ))
                    - 9_7
                )
                % 2_6
                + 9_7      )
            key_iterator += 1
            plaintext_iterator += 1
    return ciphertext


def       __a       (   SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE      )      ->     str:






    '''simple docstring'''
    if not isinstance(SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE      ):
        raise TypeError('''ciphertext must be a string'''      )
    if not isinstance(SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE      ):
        raise TypeError('''key must be a string'''      )

    if not ciphertext:
        raise ValueError('''ciphertext is empty'''      )
    if not key:
        raise ValueError('''key is empty'''      )

    __UpperCAmelCase									=			key.lower()
    __UpperCAmelCase									=			0
    __UpperCAmelCase									=			0
    __UpperCAmelCase									=			''''''
    while ciphertext_iterator < len(SCREAMING_SNAKE_CASE      ):
        if (
            ord(ciphertext[ciphertext_iterator]      ) < 9_7
            or ord(ciphertext[ciphertext_iterator]      ) > 1_2_2
        ):
            plaintext += ciphertext[ciphertext_iterator]
        else:
            plaintext += chr(
                (ord(ciphertext[ciphertext_iterator]      ) - ord(key[key_iterator]      )) % 2_6
                + 9_7      )
            key += chr(
                (ord(ciphertext[ciphertext_iterator]      ) - ord(key[key_iterator]      )) % 2_6
                + 9_7      )
            key_iterator += 1
        ciphertext_iterator += 1
    return plaintext


if __name__ == "__main__":
       import doctest

       doctest.testmod()
       A_		:			Tuple										=   int(input('Type 1 to encrypt or 2 to decrypt:'))
       if operation == 1:
              A_		:			Union[str, Any]										=   input('Typeplaintext to be encrypted:\n')
              A_		:			Any										=   input('Type the key:\n')
              print(encrypt(plaintext, key))
       elif operation == 2:
              A_		:			Dict										=   input('Type the ciphertext to be decrypted:\n')
              A_		:			List[Any]										=   input('Type the key:\n')
              print(decrypt(ciphertext, key))
       decrypt('jsqqs avvwo', 'coffee')







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_		:			Optional[int]										=   True
       from torch.cuda.amp import autocast


A_		:			List[Any]										=   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=_a ,     metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} ,     )
    a__     							=       field(
        default=_a ,     metadata={"help": "Whether to freeze the feature extractor layers of the model."}						)
    a__     							=       field(
        default=_a ,     metadata={"help": "Whether to log verbose messages or not."} ,     )






def       __a       (   SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE      )      ->     str:






    '''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      )]       ,   )
    __UpperCAmelCase									=			logging.WARNING
    if model_args.verbose_logging:
        __UpperCAmelCase									=			logging.DEBUG
    elif trainer_utils.is_main_process(training_args.local_rank      ):
        __UpperCAmelCase									=			logging.INFO
    logger.setLevel(SCREAMING_SNAKE_CASE      )
@dataclass
class 					A_   :


    '''simple docstring'''






    a__     							=       field(
        default=_a ,     metadata={"help": "The name of the dataset to use (via the datasets library)."}						)
    a__     							=       field(
        default=_a ,     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=_a ,     metadata={"help": "Resample loaded audio to target feature extractor's sampling rate or not."} ,     )
    a__     							=       field(
        default=_a ,     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=_a ,     metadata={"help": "Overwrite the cached preprocessed datasets or not."}						)
    a__     							=       field(
        default=_a ,     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=_a						)
    a__     							=       field(default_factory=_a						)
    a__     							=       None


    @classmethod
    def      lowerCAmelCase_						(cls     ,      lowercase__  )     ->      Union[str, Any]:
        if name == "librispeech":
            return cls()
        if name == "timit":
            return cls(
                do_lower_case=lowercase__     ,      translation_table=str.maketrans({'''-''': ''' '''}  )     ,      )
        if name == "buckwalter":
            __UpperCAmelCase									=			{
                '''-''': ''' ''',  # 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      lowerCAmelCase_						(self     ,      lowercase__  )     ->      str:
        # TODO(elgeish) return a pipeline (e.g., from jiwer) instead? Or rely on branch predictor as is
        if len(self.translation_table  ) > 0:
            __UpperCAmelCase									=			text.translate(self.translation_table  )
        if len(self.words_to_remove  ) == 0:
            __UpperCAmelCase									=			''' '''.join(text.split()  )  # clean up whitespaces
        else:
            __UpperCAmelCase									=			''' '''.join(w for w in text.split() if w not in self.words_to_remove  )  # and clean up whilespaces
        return text






    def      lowerCAmelCase_						(self     ,      lowercase__  )     ->      WavaVecaProcessor:
        __UpperCAmelCase									=			WavaVecaFeatureExtractor.from_pretrained(
            model_args.model_name_or_path     ,      cache_dir=model_args.cache_dir  )
        if self.vocab_file:
            __UpperCAmelCase									=			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:
            __UpperCAmelCase									=			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 					A_   :


    '''simple docstring'''






    a__     							=       42
    a__     							=       True
    a__     							=       None
    a__     							=       None
    a__     							=       None
    a__     							=       None


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

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

        __UpperCAmelCase									=			labels

        return batch






class 					A_   (      _a						):


    '''simple docstring'''






    def      lowerCAmelCase_						(self     ,      lowercase__     ,      lowercase__  )     ->      torch.Tensor:
        model.train()
        __UpperCAmelCase									=			self._prepare_inputs(lowercase__  )

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

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






    '''simple docstring'''
    # 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.

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

    __UpperCAmelCase					,     __UpperCAmelCase					,     __UpperCAmelCase									=			parser.parse_args_into_dataclasses()
    configure_logger(SCREAMING_SNAKE_CASE       ,   SCREAMING_SNAKE_CASE      )

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

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

    __UpperCAmelCase									=			datasets.load_metric('''wer'''      )
    __UpperCAmelCase									=			processor.feature_extractor.sampling_rate if data_args.target_feature_extractor_sampling_rate else None
    __UpperCAmelCase									=			''''''.join(t for t in processor.tokenizer.get_vocab().keys() if len(SCREAMING_SNAKE_CASE      ) == 1      )
    __UpperCAmelCase									=			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       ,   )
    __UpperCAmelCase									=			[]

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

    __UpperCAmelCase									=			train_dataset.map(SCREAMING_SNAKE_CASE       ,   remove_columns=[data_args.speech_file_column]      )
    __UpperCAmelCase									=			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

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

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

    __UpperCAmelCase									=			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       ,   )
    __UpperCAmelCase									=			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       ,   )

    __UpperCAmelCase									=			DataCollatorCTCWithPadding(processor=SCREAMING_SNAKE_CASE       ,   padding=SCREAMING_SNAKE_CASE      )

    def compute_metrics(SCREAMING_SNAKE_CASE      ):
        __UpperCAmelCase									=			pred.predictions
        __UpperCAmelCase									=			np.argmax(SCREAMING_SNAKE_CASE       ,   axis=-1      )

        __UpperCAmelCase									=			processor.tokenizer.pad_token_id

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

        __UpperCAmelCase									=			wer_metric.compute(predictions=SCREAMING_SNAKE_CASE       ,   references=SCREAMING_SNAKE_CASE      )

        return {"wer": wer}

    if model_args.freeze_feature_extractor:
        model.freeze_feature_extractor()

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




