




'''simple docstring'''
A				: List[str]					      =			(1, 153, 370, 371, 1_634, 24_678_051, 115_132_219_018_763_992_565_095_597_973_971_522_401)
A				: tuple					      =			(-153, -1, 0, 1.2, 200, "A", [], {}, None)
def 							snake_case_    (  a__						:      int     ):



    """simple docstring"""




    if not isinstance(a__       ,a__     ) or n < 1:
        return False

    # Initialization of sum and number of digits.
    __lowercase     							=		0
    __lowercase     							=		0
    __lowercase     							=		n
    # Calculation of digits of the number
    while temp > 0:
        number_of_digits += 1
        temp //= 10
    # Dividing number into separate digits and find Armstrong number
    __lowercase     							=		n
    while temp > 0:
        __lowercase     							=		temp % 10
        total += rem**number_of_digits
        temp //= 10
    return n == total
def 							snake_case_    (  a__						:      int     ):



    """simple docstring"""




    if not isinstance(a__       ,a__     ) or n < 1:
        return False

    # Init a "histogram" of the digits
    __lowercase     							=		[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    __lowercase     							=		0
    __lowercase     							=		0
    __lowercase     							=		n
    while temp > 0:
        __lowercase							,__lowercase     							=		divmod(a__       ,10     )
        digit_histogram[rem] += 1
        digit_total += 1

    for cnt, i in zip(a__       ,range(len(a__     )     )     ):
        total += cnt * i**digit_total

    return n == total
def 							snake_case_    (  a__						:      int     ):



    """simple docstring"""




    if not isinstance(a__       ,a__     ) or n < 1:
        return False
    __lowercase     							=		len(str(a__     )     )  # the power that all digits will be raised to
    # check if sum of each digit multiplied expo times is equal to number
    return n == sum(int(a__     ) ** expo for i in str(a__     )     )
def 							snake_case_    (  ):



    """simple docstring"""




    __lowercase     							=		int(input("""Enter an integer to see if it is an Armstrong number: """     ).strip()     )
    print(f'{num} is {"" if armstrong_number(a__     ) else "not "}an Armstrong number.'     )
    print(f'{num} is {"" if narcissistic_number(a__     ) else "not "}an Armstrong number.'     )
    print(f'{num} is {"" if pluperfect_number(a__     ) else "not "}an Armstrong number.'     )


if __name__ == "__main__":
  import doctest

  doctest.testmod()
  main()










'''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				: Union[str, Any]					      =			True
  from torch.cuda.amp import autocast


A				: Union[str, Any]					      =			logging.getLogger(__name__)






@dataclass
class 			SCREAMING_SNAKE_CASE:
       snake_case_					:	str       =   field(
           metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}	)
       snake_case_					:	Optional[str]       =   field(
           default=__A  , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}  , )
       snake_case_					:	Optional[bool]       =   field(
           default=__A  , metadata={"""help""": """Whether to freeze the feature extractor layers of the model."""}	)
       snake_case_					:	Optional[bool]       =   field(
           default=__A  , metadata={"""help""": """Whether to log verbose messages or not."""}  , )

def 							snake_case_    (  a__						:      ModelArguments       ,a__						:      TrainingArguments     ):



    """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(a__     )






@dataclass
class 			SCREAMING_SNAKE_CASE:
       snake_case_					:	str       =   field(
           default=__A  , metadata={"""help""": """The name of the dataset to use (via the datasets library)."""}	)
       snake_case_					:	Optional[str]       =   field(
           default=__A  , metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""}	)
       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'"""
           }  , )
       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'"""
               )
           }  , )
       snake_case_					:	Optional[str]       =   field(
           default="""text"""  , metadata={"""help""": """Column in the dataset that contains label (target text). Defaults to 'text'"""}  , )
       snake_case_					:	Optional[str]       =   field(
           default="""file"""  , metadata={"""help""": """Column in the dataset that contains speech file path. Defaults to 'file'"""}  , )
       snake_case_					:	Optional[bool]       =   field(
           default=__A  , metadata={"""help""": """Resample loaded audio to target feature extractor's sampling rate or not."""}  , )
       snake_case_					:	Optional[float]       =   field(
           default=__A  , metadata={"""help""": """Filters out examples longer than specified. Defaults to no filtering."""}  , )
       snake_case_					:	Optional[str]       =   field(
           default="""librispeech"""  , metadata={
               """help""": (
                   """Orthography used for normalization and tokenization: 'librispeech' (default), 'timit', or"""
                   """ 'buckwalter'."""
               )
           }  , )
       snake_case_					:	bool       =   field(
           default=__A  , metadata={"""help""": """Overwrite the cached preprocessed datasets or not."""}	)
       snake_case_					:	Optional[int]       =   field(
           default=__A  , metadata={"""help""": """The number of processes to use for the preprocessing."""}  , )






@dataclass
class 			SCREAMING_SNAKE_CASE:
       snake_case_					:	bool       =   False
       snake_case_					:	Optional[str]       =   None
       snake_case_					:	Optional[str]       =   "|"
       snake_case_					:	Optional[Dict[str, str]]       =   field(default_factory=__A	)
       snake_case_					:	Optional[Set[str]]       =   field(default_factory=__A	)
       snake_case_					:	Optional[Callable[[str], str]]       =   None

       @classmethod
       def        snake_case__     (       cls   ,						lowerCamelCase__	)       ->   Any:

           """simple docstring"""



           if name == "librispeech":
               return cls()
           if name == "timit":
               return cls(
                   do_lower_case=lowerCamelCase__   ,						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(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        snake_case__     (       self   ,						lowerCamelCase__	)       ->   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        snake_case__     (       self   ,						lowerCamelCase__	)       ->   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(lowerCamelCase__   ,						lowerCamelCase__	)






@dataclass
class 			SCREAMING_SNAKE_CASE:
       snake_case_					:	WavaVecaProcessor
       snake_case_					:	Union[bool, str]       =   True
       snake_case_					:	Optional[int]       =   None
       snake_case_					:	Optional[int]       =   None
       snake_case_					:	Optional[int]       =   None
       snake_case_					:	Optional[int]       =   None

       def __call__(       self   ,						lowerCamelCase__	)       ->   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(
               lowerCamelCase__   ,						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=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
           __lowercase     							=		labels_batch["""input_ids"""].masked_fill(labels_batch.attention_mask.ne(1	)   ,						-100	)

           __lowercase     							=		labels

           return batch






class 			SCREAMING_SNAKE_CASE(							__A	):

       def        snake_case__     (       self   ,						lowerCamelCase__   ,						lowerCamelCase__	)       ->   torch.Tensor:

           """simple docstring"""



           model.train()
           __lowercase     							=		self._prepare_inputs(lowerCamelCase__	)

           if self.use_amp:
               with autocast():
                   __lowercase     							=		self.compute_loss(lowerCamelCase__   ,						lowerCamelCase__	)
           else:
               __lowercase     							=		self.compute_loss(lowerCamelCase__   ,						lowerCamelCase__	)

           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(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 							snake_case_    (  ):



    """simple docstring"""




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

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

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

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

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

    def prepare_dataset(a__						:      Optional[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(a__     )
        return batch

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

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

    def compute_metrics(a__						:      Union[str, Any]     ):
        __lowercase     							=		pred.predictions
        __lowercase     							=		np.argmax(a__       ,axis=-1     )

        __lowercase     							=		processor.tokenizer.pad_token_id

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

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

        return {"wer": wer}

    if model_args.freeze_feature_extractor:
        model.freeze_feature_extractor()

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




