






'''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"):
  UpperCamelCase_					=				True
  from torch.cuda.amp import autocast


UpperCamelCase_					=				logging.getLogger(__name__)




@dataclass
class 					__UpperCAmelCase :

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






def  lowerCAmelCase__		(					a_  :     ModelArguments			,						a_  :     TrainingArguments			)   -> int:
       logging.basicConfig(
           format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s'''			,						datefmt='''%m/%d/%Y %H:%M:%S'''			,						handlers=[logging.StreamHandler(sys.stdout			)]			,						)
       UpperCAmelCase__	:   List[Any]												=	logging.WARNING
       if model_args.verbose_logging:
              UpperCAmelCase__	:   int												=	logging.DEBUG
       elif trainer_utils.is_main_process(training_args.local_rank			):
              UpperCAmelCase__	:   Union[str, Any]												=	logging.INFO
       logger.setLevel(_a			)




@dataclass
class 					__UpperCAmelCase :

      '''simple docstring'''





      SCREAMING_SNAKE_CASE				:    str				       =					field(
          default=__snake_case      ,				metadata={"help": "The name of the dataset to use (via the datasets library)."}	)
      SCREAMING_SNAKE_CASE				:    Optional[str]				       =					field(
          default=__snake_case      ,				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=__snake_case      ,				metadata={"help": "Resample loaded audio to target feature extractor's sampling rate or not."}      ,				)
      SCREAMING_SNAKE_CASE				:    Optional[float]				       =					field(
          default=__snake_case      ,				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=__snake_case      ,				metadata={"help": "Overwrite the cached preprocessed datasets or not."}	)
      SCREAMING_SNAKE_CASE				:    Optional[int]				       =					field(
          default=__snake_case      ,				metadata={"help": "The number of processes to use for the preprocessing."}      ,				)




@dataclass
class 					__UpperCAmelCase :

      '''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=__snake_case	)
      SCREAMING_SNAKE_CASE				:    Optional[Set[str]]				       =					field(default_factory=__snake_case	)
      SCREAMING_SNAKE_CASE				:    Optional[Callable[[str], str]]				       =					None




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




      def 							lowerCamelCase     (					self  ,		_UpperCAmelCase						):
             # TODO(elgeish) return a pipeline (e.g., from jiwer) instead? Or rely on branch predictor as is
             if len(self.translation_table						) > 0:
                    UpperCAmelCase__	:   Optional[int]												=	text.translate(self.translation_table						)
             if len(self.words_to_remove						) == 0:
                    UpperCAmelCase__	:   List[Any]												=	""" """.join(text.split()						)  # clean up whitespaces
             else:
                    UpperCAmelCase__	:   List[str]												=	""" """.join(w for w in text.split() if w not in self.words_to_remove						)  # and clean up whilespaces
             return text




      def 							lowerCamelCase     (					self  ,		_UpperCAmelCase						):
             UpperCAmelCase__	:   List[Any]												=	WavaVecaFeatureExtractor.from_pretrained(
                 model_args.model_name_or_path  ,		cache_dir=model_args.cache_dir						)
             if self.vocab_file:
                    UpperCAmelCase__	:   Tuple												=	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__	:   Tuple												=	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(lowerCamelCase_  ,		lowerCamelCase_						)




@dataclass
class 					__UpperCAmelCase :

      '''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  ,		_UpperCAmelCase						):
             # split inputs and labels since they have to be of different lenghts and need
             # different padding methods
             UpperCAmelCase__	:   Union[str, Any]												=	[{"""input_values""": feature["""input_values"""]} for feature in features]
             UpperCAmelCase__	:   List[Any]												=	[{"""input_ids""": feature["""labels"""]} for feature in features]

             UpperCAmelCase__	:   List[str]												=	self.processor.pad(
                 lowerCamelCase_  ,		padding=self.padding  ,		max_length=self.max_length  ,		pad_to_multiple_of=self.pad_to_multiple_of  ,		return_tensors='''pt'''  ,		)
             UpperCAmelCase__	:   Optional[Any]												=	self.processor.pad(
                 labels=lowerCamelCase_  ,		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__	:   Any												=	labels_batch["""input_ids"""].masked_fill(labels_batch.attention_mask.ne(1						)  ,		-100						)

             UpperCAmelCase__	:   List[str]												=	labels

             return batch




class 					__UpperCAmelCase (		__snake_case	):

      '''simple docstring'''





      def 							lowerCamelCase     (					self  ,		_UpperCAmelCase  ,		_UpperCAmelCase						):
             model.train()
             UpperCAmelCase__	:   Optional[int]												=	self._prepare_inputs(lowerCamelCase_						)

             if self.use_amp:
                    with autocast():
                           UpperCAmelCase__	:   int												=	self.compute_loss(lowerCamelCase_  ,		lowerCamelCase_						)
             else:
                    UpperCAmelCase__	:   Tuple												=	self.compute_loss(lowerCamelCase_  ,		lowerCamelCase_						)

             if self.args.n_gpu > 1:
                    if model.module.config.ctc_loss_reduction == "mean":
                           UpperCAmelCase__	:   List[str]												=	loss.mean()
                    elif model.module.config.ctc_loss_reduction == "sum":
                           UpperCAmelCase__	:   List[str]												=	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__	:   Union[str, Any]												=	loss / self.args.gradient_accumulation_steps

             if self.use_amp:
                    self.scaler.scale(lowerCamelCase_						).backward()
             elif self.use_apex:
                    with amp.scale_loss(lowerCamelCase_  ,		self.optimizer						) as scaled_loss:
                           scaled_loss.backward()
             elif self.deepspeed:
                    self.deepspeed.backward(lowerCamelCase_						)
             else:
                    loss.backward()

             return loss.detach()






def  lowerCAmelCase__		(					)   -> Optional[Any]:
       UpperCAmelCase__	:   List[Any]												=	HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)			)

       UpperCAmelCase__	:   Any												=	parser.parse_args_into_dataclasses()
       configure_logger(_a			,						_a			)

       UpperCAmelCase__	:   Tuple												=	Orthography.from_name(data_args.orthography.lower()			)
       UpperCAmelCase__	:   int												=	orthography.create_processor(_a			)
       UpperCAmelCase__	:   Dict												=	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__	:   Dict												=	datasets.load_dataset(
           data_args.dataset_name			,						data_args.dataset_config_name			,						split=data_args.train_split_name			)
       UpperCAmelCase__	:   int												=	datasets.load_dataset(
           data_args.dataset_name			,						data_args.dataset_config_name			,						split=data_args.validation_split_name			)

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

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

       UpperCAmelCase__	:   Any												=	train_dataset.map(_a			,						remove_columns=[data_args.speech_file_column]			)
       UpperCAmelCase__	:   Optional[Any]												=	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_  :     List[Any]			):
                     return example["duration_in_seconds"] <= data_args.max_duration_in_seconds

              UpperCAmelCase__	:   Union[str, Any]												=	len(_a			)
              UpperCAmelCase__	:   int												=	len(_a			)
              UpperCAmelCase__	:   Optional[Any]												=	train_dataset.filter(_a			,						remove_columns=['''duration_in_seconds''']			)
              UpperCAmelCase__	:   Tuple												=	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}\""""			)
       UpperCAmelCase__	:   Dict												=	None

       def prepare_dataset(a_  :     Optional[int]			):
              # 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__	:   List[str]												=	processor(
                  audio=batch['''speech''']			,						text=batch[data_args.target_text_column]			,						sampling_rate=batch['''sampling_rate'''][0]			)
              batch.update(_a			)
              return batch

       UpperCAmelCase__	:   int												=	train_dataset.map(
           _a			,						batch_size=training_args.per_device_train_batch_size			,						batched=_a			,						num_proc=data_args.preprocessing_num_workers			,						)
       UpperCAmelCase__	:   Optional[Any]												=	val_dataset.map(
           _a			,						batch_size=training_args.per_device_train_batch_size			,						batched=_a			,						num_proc=data_args.preprocessing_num_workers			,						)

       UpperCAmelCase__	:   Optional[int]												=	DataCollatorCTCWithPadding(processor=_a			,						padding=_a			)

       def compute_metrics(a_  :     int			):
              UpperCAmelCase__	:   List[Any]												=	pred.predictions
              UpperCAmelCase__	:   Optional[int]												=	np.argmax(_a			,						axis=-1			)

              UpperCAmelCase__	:   List[str]												=	processor.tokenizer.pad_token_id

              UpperCAmelCase__	:   str												=	processor.batch_decode(_a			)
              # we do not want to group tokens when computing the metrics
              UpperCAmelCase__	:   List[Any]												=	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			)}\""""			)

              UpperCAmelCase__	:   Dict												=	wer_metric.compute(predictions=_a			,						references=_a			)

              return {"wer": wer}

       if model_args.freeze_feature_extractor:
              model.freeze_feature_extractor()

       UpperCAmelCase__	:   Union[str, Any]												=	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()




import itertools
from pathlib import Path







def       lowerCamelCase_  (    _a       :						list[str]    ):



    '''simple docstring'''




    UpperCAmelCase_     :       Union[str, Any]  		=					[tuple(_a    ) for login in logins]

    UpperCAmelCase_     :       str  		=					{char for login in split_logins for char in login}

    for permutation in itertools.permutations(_a    ):
        UpperCAmelCase_     :       str  		=					True
        for login in logins:
            if not (
                permutation.index(login[0]    )
                < permutation.index(login[1]    )
                < permutation.index(login[2]    )
            ):
                UpperCAmelCase_     :       Optional[int]  		=					False
                break

        if satisfied:
            return int("""""".join(_a    )    )

    raise Exception("""Unable to find the secret passcode"""    )







def       lowerCamelCase_  (    _a       :						str = "keylog.txt"    ):



    '''simple docstring'''




    UpperCAmelCase_     :       Union[str, Any]  		=					Path(_a    ).parent.joinpath(_a    ).read_text().splitlines()

    return find_secret_passcode(_a    )


if __name__ == "__main__":
      print(F"{solution() = }")
