code: 
  """simple docstring"""
  
  
  
  
  
  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	 =							True
      from torch.cuda.amp import autocast
  
  
  _a	 =							logging.getLogger(__name__)
  
  
  @dataclass
  class A_			:
  
  
  
  
    '''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=lowercase__       ,metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}       ,)
    SCREAMING_SNAKE_CASE__    :		Optional[bool]						  =	field(
        default=lowercase__       ,metadata={"""help""": """Whether to freeze the feature extractor layers of the model."""}   )
    SCREAMING_SNAKE_CASE__    :		Optional[bool]						  =	field(
        default=lowercase__       ,metadata={"""help""": """Whether to log verbose messages or not."""}       ,)
  
  
  
  
  
  
  
  def 			lowercase__  (	__lowerCamelCase,	__lowerCamelCase						):
     logging.basicConfig(
         format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",	datefmt="%m/%d/%Y %H:%M:%S",	handlers=[logging.StreamHandler(sys.stdout						)],	)
     UpperCAmelCase_      :      Any      =					logging.WARNING
     if model_args.verbose_logging:
        UpperCAmelCase_      :      Tuple      =					logging.DEBUG
     elif trainer_utils.is_main_process(training_args.local_rank						):
        UpperCAmelCase_      :      Optional[int]      =					logging.INFO
     logger.setLevel(__lowerCamelCase						)
  
  
  @dataclass
  class A_			:
  
  
  
  
    '''simple docstring'''
    SCREAMING_SNAKE_CASE__    :		str						  =	field(
        default=lowercase__       ,metadata={"""help""": """The name of the dataset to use (via the datasets library)."""}   )
    SCREAMING_SNAKE_CASE__    :		Optional[str]						  =	field(
        default=lowercase__       ,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=lowercase__       ,metadata={"""help""": """Resample loaded audio to target feature extractor's sampling rate or not."""}       ,)
    SCREAMING_SNAKE_CASE__    :		Optional[float]						  =	field(
        default=lowercase__       ,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=lowercase__       ,metadata={"""help""": """Overwrite the cached preprocessed datasets or not."""}   )
    SCREAMING_SNAKE_CASE__    :		Optional[int]						  =	field(
        default=lowercase__       ,metadata={"""help""": """The number of processes to use for the preprocessing."""}       ,)
  
  
  
  
  @dataclass
  class A_			:
  
  
  
  
    '''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=lowercase__   )
    SCREAMING_SNAKE_CASE__    :		Optional[Set[str]]						  =	field(default_factory=lowercase__   )
    SCREAMING_SNAKE_CASE__    :		Optional[Callable[[str], str]]						  =	None
  
  
  
  
  
  
  
    @classmethod
    def  UpperCamelCase__      (	cls       ,     lowercase_						):
  
       """simple docstring"""
       if name == "librispeech":
          return cls()
       if name == "timit":
          return cls(
              do_lower_case=lowercase_       ,     translation_table=str.maketrans({"-": " "}						)       ,     )
       if name == "buckwalter":
          UpperCAmelCase_      :      Dict      =					{
              "-": " ",  # 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  UpperCamelCase__      (	self       ,     lowercase_						):
  
       """simple docstring"""
       # TODO(elgeish) return a pipeline (e.g., from jiwer) instead? Or rely on branch predictor as is
       if len(self.translation_table						) > 0:
          UpperCAmelCase_      :      Tuple      =					text.translate(self.translation_table						)
       if len(self.words_to_remove						) == 0:
          UpperCAmelCase_      :      Union[str, Any]      =					" ".join(text.split()						)  # clean up whitespaces
       else:
          UpperCAmelCase_      :      Optional[int]      =					" ".join(w for w in text.split() if w not in self.words_to_remove						)  # and clean up whilespaces
       return text
  
  
  
  
  
  
  
    def  UpperCamelCase__      (	self       ,     lowercase_						):
  
       """simple docstring"""
       UpperCAmelCase_      :      Any      =					WavaVecaFeatureExtractor.from_pretrained(
           model_args.model_name_or_path       ,     cache_dir=model_args.cache_dir						)
       if self.vocab_file:
          UpperCAmelCase_      :      Any      =					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_      :      Dict      =					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'''
    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       ,     lowercase_						):
  
       """simple docstring"""
       UpperCAmelCase_      :      str      =					[{"input_values": feature["input_values"]} for feature in features]
       UpperCAmelCase_      :      List[str]      =					[{"input_ids": feature["labels"]} for feature in features]
  
       UpperCAmelCase_      :      Optional[int]      =					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_      :      List[str]      =					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_      :      Tuple      =					labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1						)       ,     -100						)
  
       UpperCAmelCase_      :      Dict      =					labels
  
       return batch
  
  
  
  
  class A_			(lowercase__   ):
  
  
  
  
    '''simple docstring'''
  
  
  
  
  
  
  
    def  UpperCamelCase__      (	self       ,     lowercase_       ,     lowercase_						):
  
       """simple docstring"""
       model.train()
       UpperCAmelCase_      :      str      =					self._prepare_inputs(lowercase_						)
  
       if self.use_amp:
          with autocast():
             UpperCAmelCase_      :      List[Any]      =					self.compute_loss(lowercase_       ,     lowercase_						)
       else:
          UpperCAmelCase_      :      str      =					self.compute_loss(lowercase_       ,     lowercase_						)
  
       if self.args.n_gpu > 1:
          if model.module.config.ctc_loss_reduction == "mean":
             UpperCAmelCase_      :      Optional[int]      =					loss.mean()
          elif model.module.config.ctc_loss_reduction == "sum":
             UpperCAmelCase_      :      List[Any]      =					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_      :      Optional[int]      =					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 			lowercase__  (	):
     # 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_      :      List[str]      =					HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)						)
  
     UpperCAmelCase_      :      Tuple      =					parser.parse_args_into_dataclasses()
     configure_logger(__lowerCamelCase,	__lowerCamelCase						)
  
     UpperCAmelCase_      :      List[str]      =					Orthography.from_name(data_args.orthography.lower()						)
     UpperCAmelCase_      :      Union[str, Any]      =					orthography.create_processor(__lowerCamelCase						)
     UpperCAmelCase_      :      Optional[int]      =					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_      :      List[str]      =					datasets.load_dataset(
         data_args.dataset_name,	data_args.dataset_config_name,	split=data_args.train_split_name						)
     UpperCAmelCase_      :      Dict      =					datasets.load_dataset(
         data_args.dataset_name,	data_args.dataset_config_name,	split=data_args.validation_split_name						)
  
     UpperCAmelCase_      :      List[Any]      =					datasets.load_metric("wer"						)
     UpperCAmelCase_      :      List[Any]      =					processor.feature_extractor.sampling_rate if data_args.target_feature_extractor_sampling_rate else None
     UpperCAmelCase_      :      Optional[int]      =					"".join(t for t in processor.tokenizer.get_vocab().keys() if len(__lowerCamelCase						) == 1						)
     UpperCAmelCase_      :      Tuple      =					re.compile(  # remove characters not in vocabulary
         rf"""[^\s{re.escape(__lowerCamelCase						)}]""",	flags=re.IGNORECASE if processor.tokenizer.do_lower_case else 0,	)
     UpperCAmelCase_      :      str      =					[]
  
     def prepare_example(__lowerCamelCase						):  # TODO(elgeish) make use of multiprocessing?
        UpperCAmelCase_      :      str      =					librosa.load(example[data_args.speech_file_column],	sr=__lowerCamelCase						)
        if data_args.max_duration_in_seconds is not None:
           UpperCAmelCase_      :      Tuple      =					len(example["speech"]						) / example["sampling_rate"]
        # Normalize and clean up text; order matters!
        UpperCAmelCase_      :      Union[str, Any]      =					orthography.preprocess_for_training(example[data_args.target_text_column]						)
        UpperCAmelCase_      :      int      =					vocabulary_text_cleaner.sub("",	__lowerCamelCase						)
        if updated_text != example[data_args.target_text_column]:
           text_updates.append((example[data_args.target_text_column], updated_text)						)
           UpperCAmelCase_      :      List[Any]      =					updated_text
        return example
  
     UpperCAmelCase_      :      List[str]      =					train_dataset.map(__lowerCamelCase,	remove_columns=[data_args.speech_file_column]						)
     UpperCAmelCase_      :      Union[str, Any]      =					val_dataset.map(__lowerCamelCase,	remove_columns=[data_args.speech_file_column]						)
  
     if data_args.max_duration_in_seconds is not None:
  
        def filter_by_max_duration(__lowerCamelCase						):
           return example["duration_in_seconds"] <= data_args.max_duration_in_seconds
  
        UpperCAmelCase_      :      int      =					len(__lowerCamelCase						)
        UpperCAmelCase_      :      Optional[int]      =					len(__lowerCamelCase						)
        UpperCAmelCase_      :      int      =					train_dataset.filter(__lowerCamelCase,	remove_columns=["duration_in_seconds"]						)
        UpperCAmelCase_      :      Union[str, Any]      =					val_dataset.filter(__lowerCamelCase,	remove_columns=["duration_in_seconds"]						)
        if len(__lowerCamelCase						) > old_train_size:
           logger.warning(
               f"""Filtered out {len(__lowerCamelCase						) - old_train_size} train example(s) longer than"""
               f""" {data_args.max_duration_in_seconds} second(s)."""						)
        if len(__lowerCamelCase						) > old_val_size:
           logger.warning(
               f"""Filtered out {len(__lowerCamelCase						) - old_val_size} validation example(s) longer than"""
               f""" {data_args.max_duration_in_seconds} second(s)."""						)
     logger.info(f"""Split sizes: {len(__lowerCamelCase						)} train and {len(__lowerCamelCase						)} validation."""						)
  
     logger.warning(f"""Updated {len(__lowerCamelCase						)} 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_      :      Optional[int]      =					None
  
     def prepare_dataset(__lowerCamelCase						):
        # 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_      :      Union[str, Any]      =					processor(
            audio=batch["speech"],	text=batch[data_args.target_text_column],	sampling_rate=batch["sampling_rate"][0]						)
        batch.update(__lowerCamelCase						)
        return batch
  
     UpperCAmelCase_      :      List[Any]      =					train_dataset.map(
         __lowerCamelCase,	batch_size=training_args.per_device_train_batch_size,	batched=__lowerCamelCase,	num_proc=data_args.preprocessing_num_workers,	)
     UpperCAmelCase_      :      List[Any]      =					val_dataset.map(
         __lowerCamelCase,	batch_size=training_args.per_device_train_batch_size,	batched=__lowerCamelCase,	num_proc=data_args.preprocessing_num_workers,	)
  
     UpperCAmelCase_      :      Dict      =					DataCollatorCTCWithPadding(processor=__lowerCamelCase,	padding=__lowerCamelCase						)
  
     def compute_metrics(__lowerCamelCase						):
        UpperCAmelCase_      :      Tuple      =					pred.predictions
        UpperCAmelCase_      :      List[str]      =					np.argmax(__lowerCamelCase,	axis=-1						)
  
        UpperCAmelCase_      :      Union[str, Any]      =					processor.tokenizer.pad_token_id
  
        UpperCAmelCase_      :      str      =					processor.batch_decode(__lowerCamelCase						)
        # we do not want to group tokens when computing the metrics
        UpperCAmelCase_      :      List[str]      =					processor.batch_decode(pred.label_ids,	group_tokens=__lowerCamelCase						)
        if logger.isEnabledFor(logging.DEBUG						):
           for reference, predicted in zip(__lowerCamelCase,	__lowerCamelCase						):
              logger.debug(f"""reference: \"{reference}\""""						)
              logger.debug(f"""predicted: \"{predicted}\""""						)
              if orthography.untransliterator is not None:
                 logger.debug(f"""reference (untransliterated): \"{orthography.untransliterator(__lowerCamelCase						)}\""""						)
                 logger.debug(f"""predicted (untransliterated): \"{orthography.untransliterator(__lowerCamelCase						)}\""""						)
  
        UpperCAmelCase_      :      List[Any]      =					wer_metric.compute(predictions=__lowerCamelCase,	references=__lowerCamelCase						)
  
        return {"wer": wer}
  
     if model_args.freeze_feature_extractor:
        model.freeze_feature_extractor()
  
     UpperCAmelCase_      :      Tuple      =					CTCTrainer(
         model=__lowerCamelCase,	data_collator=__lowerCamelCase,	args=__lowerCamelCase,	compute_metrics=__lowerCamelCase,	train_dataset=__lowerCamelCase,	eval_dataset=__lowerCamelCase,	tokenizer=processor.feature_extractor,	)
  
     trainer.train()
  
  
  if __name__ == "__main__":
      main()
  
  
  
style_context: 
  """simple docstring"""
  
  
  
  
  
  from string import ascii_uppercase
  
  
  
  
  
  
  
  def 			__a  (	__lowerCamelCase,	__lowerCamelCase,	__lowerCamelCase = False,	__lowerCamelCase = ascii_uppercase						):
     UpperCAmelCase_      :      List[str]      =					keyword.upper()
     UpperCAmelCase_      :      str      =					plaintext.upper()
     UpperCAmelCase_      :      Tuple      =					set(__lowerCamelCase						)
  
     # create a list of unique characters in the keyword - their order matters
     # it determines how we will map plaintext characters to the ciphertext
     UpperCAmelCase_      :      Tuple      =					[]
     for char in keyword:
        if char in alphabet_set and char not in unique_chars:
           unique_chars.append(__lowerCamelCase						)
      # the number of those unique characters will determine the number of rows
     UpperCAmelCase_      :      Union[str, Any]      =					len(__lowerCamelCase						)
  
     # create a shifted version of the alphabet
     UpperCAmelCase_      :      Tuple      =					unique_chars + [
         char for char in alphabet if char not in unique_chars
     ]
  
     # create a modified alphabet by splitting the shifted alphabet into rows
     UpperCAmelCase_      :      List[str]      =					[
         shifted_alphabet[k : k + num_unique_chars_in_keyword]
         for k in range(0,	26,	__lowerCamelCase						)
     ]
  
     # map the alphabet characters to the modified alphabet characters
     # going 'vertically' through the modified alphabet - consider columns first
     UpperCAmelCase_      :      Tuple      =					{}
     UpperCAmelCase_      :      Dict      =					0
     for column in range(__lowerCamelCase						):
        for row in modified_alphabet:
           # if current row (the last one) is too short, break out of loop
           if len(__lowerCamelCase						) <= column:
              break
  
           # map current letter to letter in modified alphabet
           UpperCAmelCase_      :      Tuple      =					row[column]
           letter_index += 1
  
     if verbose:
        print(__lowerCamelCase						)
     # create the encrypted text by mapping the plaintext to the modified alphabet
     return "".join(mapping[char] if char in mapping else char for char in plaintext						)
  
  
  if __name__ == "__main__":
      # example use
      print(mixed_keyword('college', 'UNIVERSITY'))
  
  
  