





import json
import logging
import os
import re
import sys
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Union

import datasets
import numpy as np
import torch
import torchaudio
from packaging import version
from torch import nn

import transformers
from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaForCTC,
    WavaVecaProcessor,
    is_apex_available,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint, is_main_process


if is_apex_available():
    from apex import amp


if version.parse(version.parse(torch.__version__).base_version) >= version.parse('1.6'):
    __UpperCAmelCase					:     int	      =	True
    from torch.cuda.amp import autocast

__UpperCAmelCase					:     Any	      =	logging.getLogger(__name__)




def 						lowerCamelCase_	(		UpperCamelCase_=None			,					UpperCamelCase_=None       ):
      return field(default_factory=lambda: default			,					metadata=snake_case_       )


@dataclass
class 			lowerCamelCase						:
  UpperCAmelCase		:       str										=     field(
      metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'}  )
  UpperCAmelCase		:       Optional[Any]										=     field(
      default=SCREAMING_SNAKE_CASE__ ,					metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} ,					)
  UpperCAmelCase		:       Optional[Any]										=     field(
      default=SCREAMING_SNAKE_CASE__ ,					metadata={'help': 'Whether to freeze the feature extractor layers of the model.'}  )
  UpperCAmelCase		:       int										=     field(
      default=0.1 ,					metadata={'help': 'The dropout ratio for the attention probabilities.'}  )
  UpperCAmelCase		:       Optional[Any]										=     field(
      default=0.1 ,					metadata={'help': 'The dropout ratio for activations inside the fully connected layer.'}  )
  UpperCAmelCase		:       Optional[int]										=     field(
      default=0.1 ,					metadata={
          'help': 'The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.'
      } ,					)
  UpperCAmelCase		:       Optional[int]										=     field(
      default=0.1 ,					metadata={'help': 'The dropout probabilitiy for all 1D convolutional layers in feature extractor.'} ,					)
  UpperCAmelCase		:       Tuple										=     field(
      default=0.05 ,					metadata={
          'help': (
              'Propability of each feature vector along the time axis to be chosen as the start of the vector'
              'span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature'
              'vectors will be masked along the time axis. This is only relevant if ``apply_spec_augment is True``.'
          )
      } ,					)
  UpperCAmelCase		:       List[str]										=     field(default=0.0 ,					metadata={'help': 'The LayerDrop probability.'}  )


@dataclass
class 			lowerCamelCase						:
  UpperCAmelCase		:       int										=     field(
      default=SCREAMING_SNAKE_CASE__ ,					metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'}  )
  UpperCAmelCase		:       int										=     field(
      default='train+validation' ,					metadata={
          'help': 'The name of the training data set split to use (via the datasets library). Defaults to \'train\''
      } ,					)
  UpperCAmelCase		:       Dict										=     field(
      default=SCREAMING_SNAKE_CASE__ ,					metadata={'help': 'Overwrite the cached preprocessed datasets or not.'}  )
  UpperCAmelCase		:       Tuple										=     field(
      default=SCREAMING_SNAKE_CASE__ ,					metadata={'help': 'The number of processes to use for the preprocessing.'} ,					)
  UpperCAmelCase		:       List[str]										=     field(
      default=SCREAMING_SNAKE_CASE__ ,					metadata={
          'help': (
              'For debugging purposes or quicker training, truncate the number of training examples to this '
              'value if set.'
          )
      } ,					)
  UpperCAmelCase		:       Optional[Any]										=     field(
      default=SCREAMING_SNAKE_CASE__ ,					metadata={
          'help': (
              'For debugging purposes or quicker training, truncate the number of validation examples to this '
              'value if set.'
          )
      } ,					)
  UpperCAmelCase		:       Dict										=     list_field(
      default=[',', '?', '.', '!', '-', ';', ':', '\"\"', '%', '\'', '\"', '�'] ,					metadata={'help': 'A list of characters to remove from the transcripts.'} ,					)


@dataclass
class 			lowerCamelCase						:
  UpperCAmelCase		:       List[str]										=     4_2
  UpperCAmelCase		:       Dict										=     True
  UpperCAmelCase		:       int										=     None
  UpperCAmelCase		:       Any										=     None
  UpperCAmelCase		:       Optional[int]										=     None
  UpperCAmelCase		:       Union[str, Any]										=     None







  def __call__(     self						:   int  ,					__snake_case						:   Optional[int]       )    ->		int:
        _a							:  List[str]				= [{'''input_values''': feature['''input_values''']} for feature in features]
        _a							:  List[Any]				= [{'''input_ids''': feature['''labels''']} for feature in features]

        _a							:  Union[str, Any]				= self.processor.pad(
            __lowerCamelCase  ,					padding=self.padding  ,					max_length=self.max_length  ,					pad_to_multiple_of=self.pad_to_multiple_of  ,					return_tensors='''pt'''  ,					)
        _a							:  Tuple				= 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
        _a							:  List[Any]				= labels_batch['''input_ids'''].masked_fill(labels_batch.attention_mask.ne(1       )  ,					-100       )

        _a							:  Dict				= labels

        return batch


class 			lowerCamelCase						(		SCREAMING_SNAKE_CASE__  ):







  def      snake_case_							(     self						:   Union[str, Any]  ,					__snake_case						:   List[Any]  ,					__snake_case						:   Optional[int]       )    ->		List[str]:
        model.train()
        _a							:  Dict				= self._prepare_inputs(__lowerCamelCase       )

        if self.use_amp:
              with autocast():
                    _a							:  Any				= self.compute_loss(__lowerCamelCase  ,					__lowerCamelCase       )
        else:
              _a							:  Any				= self.compute_loss(__lowerCamelCase  ,					__lowerCamelCase       )

        if self.args.n_gpu > 1:
              if model.module.config.ctc_loss_reduction == "mean":
                    _a							:  List[Any]				= loss.mean()
              elif model.module.config.ctc_loss_reduction == "sum":
                    _a							:  Optional[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:
              _a							:  int				= 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_	(		):
      _a							:  Optional[Any]				= HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)       )
      if len(sys.argv       ) == 2 and sys.argv[1].endswith('''.json'''       ):
            # If we pass only one argument to the script and it's the path to a json file,
            # let's parse it to get our arguments.
            _a							:  Optional[Any]				= parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]       )       )
      else:
            _a							:  str				= parser.parse_args_into_dataclasses()

      # Detecting last checkpoint.
      _a							:  Union[str, Any]				= None
      if os.path.isdir(training_args.output_dir       ) and training_args.do_train and not training_args.overwrite_output_dir:
            _a							:  int				= get_last_checkpoint(training_args.output_dir       )
            if last_checkpoint is None and len(os.listdir(training_args.output_dir       )       ) > 0:
                  raise ValueError(
                      f"""Output directory ({training_args.output_dir}) already exists and is not empty. """
                      '''Use --overwrite_output_dir to overcome.'''       )
            elif last_checkpoint is not None:
                  logger.info(
                      f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """
                      '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'''       )

    # Setup logging
      logging.basicConfig(
          format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s'''			,					datefmt='''%m/%d/%Y %H:%M:%S'''			,					handlers=[logging.StreamHandler(sys.stdout       )]			,					)
      logger.setLevel(logging.INFO if is_main_process(training_args.local_rank       ) else logging.WARN       )

      # Log on each process the small summary:
      logger.warning(
          f"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"""
          + f"""distributed training: {bool(training_args.local_rank != -1       )}, 16-bits training: {training_args.fpaa}"""       )
      # Set the verbosity to info of the Transformers logger (on main process only):
      if is_main_process(training_args.local_rank       ):
            transformers.utils.logging.set_verbosity_info()
      logger.info('''Training/evaluation parameters %s'''			,					snake_case_       )

      # Set seed before initializing model.
      set_seed(training_args.seed       )

      # Get the datasets:
      _a							:  Optional[Any]				= datasets.load_dataset(
          '''common_voice'''			,					data_args.dataset_config_name			,					split=data_args.train_split_name       )
      _a							:  int				= datasets.load_dataset('''common_voice'''			,					data_args.dataset_config_name			,					split='''test'''       )

      # Create and save tokenizer
      _a							:  int				= f"""[{"".join(data_args.chars_to_ignore       )}]"""

      def remove_special_characters(UpperCamelCase_       ):
            _a							:  Union[str, Any]				= re.sub(snake_case_			,					''''''			,					batch['''sentence''']       ).lower() + ''' '''
            return batch

      _a							:  int				= train_dataset.map(snake_case_			,					remove_columns=['''sentence''']       )
      _a							:  Union[str, Any]				= eval_dataset.map(snake_case_			,					remove_columns=['''sentence''']       )

      def extract_all_chars(UpperCamelCase_       ):
            _a							:  Tuple				= ''' '''.join(batch['''text''']       )
            _a							:  List[str]				= list(set(snake_case_       )       )
            return {"vocab": [vocab], "all_text": [all_text]}

      _a							:  List[str]				= train_dataset.map(
          snake_case_			,					batched=snake_case_			,					batch_size=-1			,					keep_in_memory=snake_case_			,					remove_columns=train_dataset.column_names			,					)
      _a							:  Dict				= train_dataset.map(
          snake_case_			,					batched=snake_case_			,					batch_size=-1			,					keep_in_memory=snake_case_			,					remove_columns=eval_dataset.column_names			,					)

      _a							:  Union[str, Any]				= list(set(vocab_train['''vocab'''][0]       ) | set(vocab_test['''vocab'''][0]       )       )
      _a							:  int				= {v: k for k, v in enumerate(snake_case_       )}
      _a							:  str				= vocab_dict[''' ''']
      del vocab_dict[" "]
      _a							:  str				= len(snake_case_       )
      _a							:  Any				= len(snake_case_       )

      with open('''vocab.json'''			,					'''w'''       ) as vocab_file:
            json.dump(snake_case_			,					snake_case_       )

      # Load pretrained model and tokenizer
      #
      # Distributed training:
      # The .from_pretrained methods guarantee that only one local process can concurrently
      # download model & vocab.
      _a							:  Any				= WavaVecaCTCTokenizer(
          '''vocab.json'''			,					unk_token='''[UNK]'''			,					pad_token='''[PAD]'''			,					word_delimiter_token='''|'''			,					)
      _a							:  Optional[int]				= WavaVecaFeatureExtractor(
          feature_size=1			,					sampling_rate=1_6000			,					padding_value=0.0			,					do_normalize=snake_case_			,					return_attention_mask=snake_case_       )
      _a							:  List[str]				= WavaVecaProcessor(feature_extractor=snake_case_			,					tokenizer=snake_case_       )
      _a							:  Optional[int]				= WavaVecaForCTC.from_pretrained(
          model_args.model_name_or_path			,					cache_dir=model_args.cache_dir			,					activation_dropout=model_args.activation_dropout			,					attention_dropout=model_args.attention_dropout			,					hidden_dropout=model_args.hidden_dropout			,					feat_proj_dropout=model_args.feat_proj_dropout			,					mask_time_prob=model_args.mask_time_prob			,					gradient_checkpointing=training_args.gradient_checkpointing			,					layerdrop=model_args.layerdrop			,					ctc_loss_reduction='''mean'''			,					pad_token_id=processor.tokenizer.pad_token_id			,					vocab_size=len(processor.tokenizer       )			,					)

      if data_args.max_train_samples is not None:
            _a							:  str				= min(len(snake_case_       )			,					data_args.max_train_samples       )
            _a							:  Optional[Any]				= train_dataset.select(range(snake_case_       )       )

      if data_args.max_val_samples is not None:
            _a							:  List[str]				= eval_dataset.select(range(data_args.max_val_samples       )       )

      _a							:  Optional[int]				= torchaudio.transforms.Resample(4_8000			,					1_6000       )

      # Preprocessing the datasets.
      # We need to read the aduio files as arrays and tokenize the targets.
      def speech_file_to_array_fn(UpperCamelCase_       ):
            _a							:  Any				= torchaudio.load(batch['''path''']       )
            _a							:  Optional[Any]				= resampler(snake_case_       ).squeeze().numpy()
            _a							:  Optional[Any]				= 1_6000
            _a							:  List[Any]				= batch['''text''']
            return batch

      _a							:  Dict				= train_dataset.map(
          snake_case_			,					remove_columns=train_dataset.column_names			,					num_proc=data_args.preprocessing_num_workers			,					)
      _a							:  Union[str, Any]				= eval_dataset.map(
          snake_case_			,					remove_columns=eval_dataset.column_names			,					num_proc=data_args.preprocessing_num_workers			,					)

      def prepare_dataset(UpperCamelCase_       ):
            # 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}."""

            _a							:  Tuple				= processor(
                audio=batch['''speech''']			,					text=batch['''target_text''']			,					sampling_rate=batch['''sampling_rate'''][0]       )
            batch.update(snake_case_       )
            return batch

      _a							:  List[Any]				= train_dataset.map(
          snake_case_			,					remove_columns=train_dataset.column_names			,					batch_size=training_args.per_device_train_batch_size			,					batched=snake_case_			,					num_proc=data_args.preprocessing_num_workers			,					)
      _a							:  List[str]				= eval_dataset.map(
          snake_case_			,					remove_columns=eval_dataset.column_names			,					batch_size=training_args.per_device_train_batch_size			,					batched=snake_case_			,					num_proc=data_args.preprocessing_num_workers			,					)

      # Metric
      _a							:  str				= datasets.load_metric('''wer'''       )

      def compute_metrics(UpperCamelCase_       ):
            _a							:  Optional[Any]				= pred.predictions
            _a							:  Any				= np.argmax(snake_case_			,					axis=-1       )

            _a							:  Optional[int]				= processor.tokenizer.pad_token_id

            _a							:  List[Any]				= processor.batch_decode(snake_case_       )
            # we do not want to group tokens when computing the metrics
            _a							:  str				= processor.batch_decode(pred.label_ids			,					group_tokens=snake_case_       )

            _a							:  int				= wer_metric.compute(predictions=snake_case_			,					references=snake_case_       )

            return {"wer": wer}

      if model_args.freeze_feature_extractor:
            model.freeze_feature_extractor()

      # Data collator
      _a							:  Dict				= DataCollatorCTCWithPadding(processor=snake_case_			,					padding=snake_case_       )

      # Initialize our Trainer
      _a							:  Optional[Any]				= CTCTrainer(
          model=snake_case_			,					data_collator=snake_case_			,					args=snake_case_			,					compute_metrics=snake_case_			,					train_dataset=train_dataset if training_args.do_train else None			,					eval_dataset=eval_dataset if training_args.do_eval else None			,					tokenizer=processor.feature_extractor			,					)

      # Training
      if training_args.do_train:
            if last_checkpoint is not None:
                  _a							:  Optional[Any]				= last_checkpoint
            elif os.path.isdir(model_args.model_name_or_path       ):
                  _a							:  Tuple				= model_args.model_name_or_path
            else:
                  _a							:  int				= None

            # Save the feature_extractor and the tokenizer
            if is_main_process(training_args.local_rank       ):
                  processor.save_pretrained(training_args.output_dir       )

            _a							:  Union[str, Any]				= trainer.train(resume_from_checkpoint=snake_case_       )
            trainer.save_model()

            _a							:  Tuple				= train_result.metrics
            _a							:  Any				= (
                data_args.max_train_samples if data_args.max_train_samples is not None else len(snake_case_       )
            )
            _a							:  Union[str, Any]				= min(snake_case_			,					len(snake_case_       )       )

            trainer.log_metrics('''train'''			,					snake_case_       )
            trainer.save_metrics('''train'''			,					snake_case_       )
            trainer.save_state()

      # Evaluation
      _a							:  Optional[int]				= {}
      if training_args.do_eval:
            logger.info('''*** Evaluate ***'''       )
            _a							:  Tuple				= trainer.evaluate()
            _a							:  Union[str, Any]				= data_args.max_val_samples if data_args.max_val_samples is not None else len(snake_case_       )
            _a							:  Tuple				= min(snake_case_			,					len(snake_case_       )       )

            trainer.log_metrics('''eval'''			,					snake_case_       )
            trainer.save_metrics('''eval'''			,					snake_case_       )

      return results


if __name__ == "__main__":
    main()












"""simple docstring"""



def 						__lowercase	(  snake_case_    :    int		)  ->int:



    '''simple docstring'''







    __A       :		str							=	1
    for i in range(1							,num + 1		):
        fact *= i
    return fact







def 						__lowercase	(  snake_case_    :    int		)  ->int:



    '''simple docstring'''







    __A       :		str							=	0
    while number > 0:
        __A       :		Optional[int]							=	number % 10
        sum_of_digits += last_digit
        __A       :		Dict							=	number // 10  # Removing the last_digit from the given number
    return sum_of_digits







def 						__lowercase	(  snake_case_    :    int = 100		)  ->int:



    '''simple docstring'''







    __A       :		Optional[int]							=	factorial(snake_case_		)
    __A       :		Optional[Any]							=	split_and_add(snake_case_		)
    return result


if __name__ == "__main__":
       print(solution(int(input("""Enter the Number: """).strip())))




