
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"):
							lowercase__	:Optional[int]										=					True
							from torch.cuda.amp import autocast

lowercase__	:Any										=					logging.getLogger(__name__)



def  UpperCamelCase					(							lowerCAmelCase__=None				,    lowerCAmelCase__=None	):
					'''simple docstring'''
					return field(default_factory=lambda: default				,    metadata=lowerCAmelCase__	)







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







@dataclass
class        lowercase	:
							lowercase_ : Optional[str]       =field(
							    default=SCREAMING_SNAKE_CASE__ ,						metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''}	)
							lowercase_ : 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\''''
							    } ,						)
							lowercase_ : bool       =field(
							    default=SCREAMING_SNAKE_CASE__ ,						metadata={'''help''': '''Overwrite the cached preprocessed datasets or not.'''}	)
							lowercase_ : Optional[int]       =field(
							    default=SCREAMING_SNAKE_CASE__ ,						metadata={'''help''': '''The number of processes to use for the preprocessing.'''} ,						)
							lowercase_ : Optional[int]       =field(
							    default=SCREAMING_SNAKE_CASE__ ,						metadata={
							        '''help''': (
							            '''For debugging purposes or quicker training, truncate the number of training examples to this '''
							            '''value if set.'''
							        )
							    } ,						)
							lowercase_ : Optional[int]       =field(
							    default=SCREAMING_SNAKE_CASE__ ,						metadata={
							        '''help''': (
							            '''For debugging purposes or quicker training, truncate the number of validation examples to this '''
							            '''value if set.'''
							        )
							    } ,						)
							lowercase_ : List[str]       =list_field(
							    default=[''',''', '''?''', '''.''', '''!''', '''-''', ''';''', ''':''', '''""''', '''%''', '''\'''', '''"''', '''�'''] ,						metadata={'''help''': '''A list of characters to remove from the transcripts.'''} ,						)







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




							def __call__(       self     ,A__):
												# split inputs and labels since they have to be of different lenghts and need
												# different padding methods
												lowercase					=		[{'''input_values''': feature['''input_values''']} for feature in features]
												lowercase					=		[{'''input_ids''': feature['''labels''']} for feature in features]

												lowercase					=		self.processor.pad(
												    A__     ,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=A__     ,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)     ,-1_0_0)

												lowercase					=		labels

												return batch







class        lowercase	(      SCREAMING_SNAKE_CASE__	):




							def 				A__   (       self     ,A__     ,A__):
												model.train()
												lowercase					=		self._prepare_inputs(A__)

												if self.use_amp:
																	with autocast():
																						lowercase					=		self.compute_loss(A__     ,A__)
												else:
																	lowercase					=		self.compute_loss(A__     ,A__)

												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(A__).backward()
												elif self.use_apex:
																	with amp.scale_loss(A__     ,self.optimizer) as scaled_loss:
																						scaled_loss.backward()
												elif self.deepspeed:
																	self.deepspeed.backward(A__)
												else:
																	loss.backward()

												return loss.detach()



def  UpperCamelCase					(							):
					'''simple docstring'''
					# 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.

					lowercase					=		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.
										lowercase			,		lowercase			,		lowercase					=		parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]	)	)
					else:
										lowercase			,		lowercase			,		lowercase					=		parser.parse_args_into_dataclasses()

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

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

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

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

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

					lowercase					=		train_dataset.map(lowerCAmelCase__				,    remove_columns=['''sentence''']	)
					lowercase					=		eval_dataset.map(lowerCAmelCase__				,    remove_columns=['''sentence''']	)

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

					lowercase					=		train_dataset.map(
					    lowerCAmelCase__				,    batched=lowerCAmelCase__				,    batch_size=-1				,    keep_in_memory=lowerCAmelCase__				,    remove_columns=train_dataset.column_names				,    )
					lowercase					=		train_dataset.map(
					    lowerCAmelCase__				,    batched=lowerCAmelCase__				,    batch_size=-1				,    keep_in_memory=lowerCAmelCase__				,    remove_columns=eval_dataset.column_names				,    )

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

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

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

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

					lowercase					=		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(lowerCAmelCase__	):
										lowercase			,		lowercase					=		torchaudio.load(batch['''path''']	)
										lowercase					=		resampler(lowerCAmelCase__	).squeeze().numpy()
										lowercase					=		1_6000
										lowercase					=		batch['''text''']
										return batch

					lowercase					=		train_dataset.map(
					    lowerCAmelCase__				,    remove_columns=train_dataset.column_names				,    num_proc=data_args.preprocessing_num_workers				,    )
					lowercase					=		eval_dataset.map(
					    lowerCAmelCase__				,    remove_columns=eval_dataset.column_names				,    num_proc=data_args.preprocessing_num_workers				,    )

					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}.'

										lowercase					=		processor(
										    audio=batch['''speech''']				,    text=batch['''target_text''']				,    sampling_rate=batch['''sampling_rate'''][0]	)
										batch.update(lowerCAmelCase__	)
										return batch

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

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

					def compute_metrics(lowerCAmelCase__	):
										lowercase					=		pred.predictions
										lowercase					=		np.argmax(lowerCAmelCase__				,    axis=-1	)

										lowercase					=		processor.tokenizer.pad_token_id

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

										lowercase					=		wer_metric.compute(predictions=lowerCAmelCase__				,    references=lowerCAmelCase__	)

										return {"wer": wer}

					if model_args.freeze_feature_extractor:
										model.freeze_feature_extractor()

					# Data collator
					lowercase					=		DataCollatorCTCWithPadding(processor=lowerCAmelCase__				,    padding=lowerCAmelCase__	)

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

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

										lowercase					=		trainer.train(resume_from_checkpoint=lowerCAmelCase__	)
										trainer.save_model()

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

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

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

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

					return results


if __name__ == "__main__":
							main()






from __future__ import annotations

from decimal import Decimal
from math import *  # noqa: F403

from sympy import diff



def  UpperCamelCase					(							lowerCAmelCase__				,    lowerCAmelCase__				,    lowerCAmelCase__ = 10**-10	):
					'''simple docstring'''
					lowercase					=		a
					while True:
										lowercase					=		Decimal(lowerCAmelCase__	) - (
										    Decimal(eval(lowerCAmelCase__	)	) / Decimal(eval(str(diff(lowerCAmelCase__	)	)	)	)  # noqa: S307
										)
										# This number dictates the accuracy of the answer
										if abs(eval(lowerCAmelCase__	)	) < precision:  # noqa: S307
															return float(lowerCAmelCase__	)


# Let's Execute
if __name__ == "__main__":
							# Find root of trigonometric function
							# Find value of pi
							print(F'The root of sin(x) = 0 is {newton_raphson("sin(x)", 2)}')
							# Find root of polynomial
							print(F'The root of x**2 - 5*x + 2 = 0 is {newton_raphson("x**2 - 5*x + 2", 0.4)}')
							# Find Square Root of 5
							print(F'The root of log(x) - 1 = 0 is {newton_raphson("log(x) - 1", 2)}')
							# Exponential Roots
							print(F'The root of exp(x) - 1 = 0 is {newton_raphson("exp(x) - 1", 0)}')




