


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'''):
 __snake_case		:List[Any]   	=  True
 from torch.cuda.amp import autocast

__snake_case		:Tuple   	=  logging.getLogger(__name__)





def   __snake_case			(    _UpperCAmelCase=None     ,				_UpperCAmelCase=None       ):
    return field(default_factory=lambda: default     ,				metadata=_UpperCAmelCase       )

@dataclass
class 					_A :
       UpperCamelCase__						:					str		      =		field(
           metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''}					)
       UpperCamelCase__						:					Optional[str]		      =		field(
           default=_lowerCAmelCase   ,metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''}   ,)
       UpperCamelCase__						:					Optional[bool]		      =		field(
           default=_lowerCAmelCase   ,metadata={'''help''': '''Whether to freeze the feature extractor layers of the model.'''}					)
       UpperCamelCase__						:					Optional[float]		      =		field(
           default=0.1   ,metadata={'''help''': '''The dropout ratio for the attention probabilities.'''}					)
       UpperCamelCase__						:					Optional[float]		      =		field(
           default=0.1   ,metadata={'''help''': '''The dropout ratio for activations inside the fully connected layer.'''}					)
       UpperCamelCase__						:					Optional[float]		      =		field(
           default=0.1   ,metadata={
               '''help''': '''The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.'''
           }   ,)
       UpperCamelCase__						:					Optional[float]		      =		field(
           default=0.1   ,metadata={'''help''': '''The dropout probabilitiy for all 1D convolutional layers in feature extractor.'''}   ,)
       UpperCamelCase__						:					Optional[float]		      =		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__						:					Optional[float]		      =		field(default=0.0   ,metadata={'''help''': '''The LayerDrop probability.'''}					)


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


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



       def __call__(	self							:  Tuple  ,	__SCREAMING_SNAKE_CASE							:  List[Dict[str, Union[List[int], torch.Tensor]]]):


           '''simple docstring'''

           __a		 =       [{'''input_values''': feature['''input_values''']} for feature in features]
           __a		 =       [{'''input_ids''': feature['''labels''']} for feature in features]

           __a		 =       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		 =       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		 =       labels_batch['''input_ids'''].masked_fill(labels_batch.attention_mask.ne(1)  ,	-100)

           __a		 =       labels

           return batch


class 					_A (			_lowerCAmelCase					):



       def 	_lowerCamelCase    (	self							:  List[Any]  ,	__SCREAMING_SNAKE_CASE							:  nn.Module  ,	__SCREAMING_SNAKE_CASE							:  Dict[str, Union[torch.Tensor, Any]]):


           '''simple docstring'''

           model.train()
           __a		 =       self._prepare_inputs(_lowerCAmelCase)

           if self.use_amp:
               with autocast():
                   __a		 =       self.compute_loss(_lowerCAmelCase  ,	_lowerCAmelCase)
           else:
               __a		 =       self.compute_loss(_lowerCAmelCase  ,	_lowerCAmelCase)

           if self.args.n_gpu > 1:
               if model.module.config.ctc_loss_reduction == "mean":
                   __a		 =       loss.mean()
               elif model.module.config.ctc_loss_reduction == "sum":
                   __a		 =       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		 =       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			(    ):
    __a		 =       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 ,     __a ,     __a		 =       parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]       )       )
    else:
        __a ,     __a ,     __a		 =       parser.parse_args_into_dataclasses()

    # Detecting last checkpoint.
    __a		 =       None
    if os.path.isdir(training_args.output_dir       ) and training_args.do_train and not training_args.overwrite_output_dir:
        __a		 =       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'''     ,				_UpperCAmelCase       )

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

    # Get the datasets:
    __a		 =       datasets.load_dataset(
        '''common_voice'''     ,				data_args.dataset_config_name     ,				split=data_args.train_split_name       )
    __a		 =       datasets.load_dataset('''common_voice'''     ,				data_args.dataset_config_name     ,				split='''test'''       )

    # Create and save tokenizer
    __a		 =       f'[{"".join(data_args.chars_to_ignore       )}]'

    def remove_special_characters(_UpperCAmelCase       ):
        __a		 =       re.sub(_UpperCAmelCase     ,				''''''     ,				batch['''sentence''']       ).lower() + ''' '''
        return batch

    __a		 =       train_dataset.map(_UpperCAmelCase     ,				remove_columns=['''sentence''']       )
    __a		 =       eval_dataset.map(_UpperCAmelCase     ,				remove_columns=['''sentence''']       )

    def extract_all_chars(_UpperCAmelCase       ):
        __a		 =       ''' '''.join(batch['''text''']       )
        __a		 =       list(set(_UpperCAmelCase       )       )
        return {"vocab": [vocab], "all_text": [all_text]}

    __a		 =       train_dataset.map(
        _UpperCAmelCase     ,				batched=_UpperCAmelCase     ,				batch_size=-1     ,				keep_in_memory=_UpperCAmelCase     ,				remove_columns=train_dataset.column_names     ,				)
    __a		 =       train_dataset.map(
        _UpperCAmelCase     ,				batched=_UpperCAmelCase     ,				batch_size=-1     ,				keep_in_memory=_UpperCAmelCase     ,				remove_columns=eval_dataset.column_names     ,				)

    __a		 =       list(set(vocab_train['''vocab'''][0]       ) | set(vocab_test['''vocab'''][0]       )       )
    __a		 =       {v: k for k, v in enumerate(_UpperCAmelCase       )}
    __a		 =       vocab_dict[''' ''']
    del vocab_dict[" "]
    __a		 =       len(_UpperCAmelCase       )
    __a		 =       len(_UpperCAmelCase       )

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

    # Load pretrained model and tokenizer
    #
    # Distributed training:
    # The .from_pretrained methods guarantee that only one local process can concurrently
    # download model & vocab.
    __a		 =       WavaVecaCTCTokenizer(
        '''vocab.json'''     ,				unk_token='''[UNK]'''     ,				pad_token='''[PAD]'''     ,				word_delimiter_token='''|'''     ,				)
    __a		 =       WavaVecaFeatureExtractor(
        feature_size=1     ,				sampling_rate=16000     ,				padding_value=0.0     ,				do_normalize=_UpperCAmelCase     ,				return_attention_mask=_UpperCAmelCase       )
    __a		 =       WavaVecaProcessor(feature_extractor=_UpperCAmelCase     ,				tokenizer=_UpperCAmelCase       )
    __a		 =       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		 =       min(len(_UpperCAmelCase       )     ,				data_args.max_train_samples       )
        __a		 =       train_dataset.select(range(_UpperCAmelCase       )       )

    if data_args.max_val_samples is not None:
        __a		 =       eval_dataset.select(range(data_args.max_val_samples       )       )

    __a		 =       torchaudio.transforms.Resample(48000     ,				16000       )

    # Preprocessing the datasets.
    # We need to read the aduio files as arrays and tokenize the targets.
    def speech_file_to_array_fn(_UpperCAmelCase       ):
        __a ,     __a		 =       torchaudio.load(batch['''path''']       )
        __a		 =       resampler(_UpperCAmelCase       ).squeeze().numpy()
        __a		 =       16000
        __a		 =       batch['''text''']
        return batch

    __a		 =       train_dataset.map(
        _UpperCAmelCase     ,				remove_columns=train_dataset.column_names     ,				num_proc=data_args.preprocessing_num_workers     ,				)
    __a		 =       eval_dataset.map(
        _UpperCAmelCase     ,				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		 =       processor(
            audio=batch['''speech''']     ,				text=batch['''target_text''']     ,				sampling_rate=batch['''sampling_rate'''][0]       )
        batch.update(_UpperCAmelCase       )
        return batch

    __a		 =       train_dataset.map(
        _UpperCAmelCase     ,				remove_columns=train_dataset.column_names     ,				batch_size=training_args.per_device_train_batch_size     ,				batched=_UpperCAmelCase     ,				num_proc=data_args.preprocessing_num_workers     ,				)
    __a		 =       eval_dataset.map(
        _UpperCAmelCase     ,				remove_columns=eval_dataset.column_names     ,				batch_size=training_args.per_device_train_batch_size     ,				batched=_UpperCAmelCase     ,				num_proc=data_args.preprocessing_num_workers     ,				)

    # Metric
    __a		 =       datasets.load_metric('''wer'''       )

    def compute_metrics(_UpperCAmelCase       ):
        __a		 =       pred.predictions
        __a		 =       np.argmax(_UpperCAmelCase     ,				axis=-1       )

        __a		 =       processor.tokenizer.pad_token_id

        __a		 =       processor.batch_decode(_UpperCAmelCase       )
        # we do not want to group tokens when computing the metrics
        __a		 =       processor.batch_decode(pred.label_ids     ,				group_tokens=_UpperCAmelCase       )

        __a		 =       wer_metric.compute(predictions=_UpperCAmelCase     ,				references=_UpperCAmelCase       )

        return {"wer": wer}

    if model_args.freeze_feature_extractor:
        model.freeze_feature_extractor()

    # Data collator
    __a		 =       DataCollatorCTCWithPadding(processor=_UpperCAmelCase     ,				padding=_UpperCAmelCase       )

    # Initialize our Trainer
    __a		 =       CTCTrainer(
        model=_UpperCAmelCase     ,				data_collator=_UpperCAmelCase     ,				args=_UpperCAmelCase     ,				compute_metrics=_UpperCAmelCase     ,				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		 =       last_checkpoint
        elif os.path.isdir(model_args.model_name_or_path       ):
            __a		 =       model_args.model_name_or_path
        else:
            __a		 =       None

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

        __a		 =       trainer.train(resume_from_checkpoint=_UpperCAmelCase       )
        trainer.save_model()

        __a		 =       train_result.metrics
        __a		 =       (
            data_args.max_train_samples if data_args.max_train_samples is not None else len(_UpperCAmelCase       )
        )
        __a		 =       min(_UpperCAmelCase     ,				len(_UpperCAmelCase       )       )

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

    # Evaluation
    __a		 =       {}
    if training_args.do_eval:
        logger.info('''*** Evaluate ***'''       )
        __a		 =       trainer.evaluate()
        __a		 =       data_args.max_val_samples if data_args.max_val_samples is not None else len(_UpperCAmelCase       )
        __a		 =       min(_UpperCAmelCase     ,				len(_UpperCAmelCase       )       )

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

    return results


if __name__ == "__main__":
 main()










from __future__ import annotations





def   __snake_case			(    _UpperCAmelCase     ,				_UpperCAmelCase       ):
    print(f'Vertex\tShortest Distance from vertex {src}'       )
    for i, d in enumerate(_UpperCAmelCase       ):
        print(f'{i}\t\t{d}'       )





def   __snake_case			(    _UpperCAmelCase     ,				_UpperCAmelCase     ,				_UpperCAmelCase       ):
    for j in range(_UpperCAmelCase       ):
        __a ,     __a ,     __a		 =       (graph[j][k] for k in ['''src''', '''dst''', '''weight'''])
        if distance[u] != float('''inf'''       ) and distance[u] + w < distance[v]:
            return True
    return False





def   __snake_case			(    _UpperCAmelCase     ,				_UpperCAmelCase     ,				_UpperCAmelCase     ,				_UpperCAmelCase       ):
    __a		 =       [float('''inf'''       )] * vertex_count
    __a		 =       0.0

    for _ in range(vertex_count - 1       ):
        for j in range(_UpperCAmelCase       ):
            __a ,     __a ,     __a		 =       (graph[j][k] for k in ['''src''', '''dst''', '''weight'''])

            if distance[u] != float('''inf'''       ) and distance[u] + w < distance[v]:
                __a		 =       distance[u] + w

    __a		 =       check_negative_cycle(_UpperCAmelCase     ,				_UpperCAmelCase     ,				_UpperCAmelCase       )
    if negative_cycle_exists:
        raise Exception('''Negative cycle found'''       )

    return distance


if __name__ == "__main__":
 import doctest

 doctest.testmod()

 __snake_case		:Dict   	=  int(input('''Enter number of vertices: ''').strip())
 __snake_case		:Any   	=  int(input('''Enter number of edges: ''').strip())

 __snake_case		:list[dict[str, int]]   	=  [{} for _ in range(E)]

 for i in range(E):
  print('''Edge ''', i + 1)
  __snake_case	,__snake_case	,__snake_case		:int   	=  (
      int(x)
      for x in input('''Enter source, destination, weight: ''').strip().split(''' ''')
  )
  __snake_case		:Any   	=  {'''src''': src, '''dst''': dest, '''weight''': weight}

 __snake_case		:List[str]   	=  int(input('''\nEnter shortest path source:''').strip())
 __snake_case		:Optional[Any]   	=  bellman_ford(graph, V, E, source)
 print_distance(shortest_distance, 0)





