



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

_lowerCAmelCase	:   Optional[int]    =   logging.getLogger(__name__)







def     UpperCAmelCase_		(					snake_case__=None    ,			snake_case__=None					)	->     Tuple:



				"""simple docstring"""





				return field(default_factory=lambda: default    ,			metadata=snake_case__					)


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



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



@dataclass
class 	__snake_case   :
		SCREAMING_SNAKE_CASE__								=	42
		SCREAMING_SNAKE_CASE__								=	True
		SCREAMING_SNAKE_CASE__								=	None
		SCREAMING_SNAKE_CASE__								=	None
		SCREAMING_SNAKE_CASE__								=	None
		SCREAMING_SNAKE_CASE__								=	None
		def __call__(							self    ,a_						):







						"""simple docstring"""
						# split inputs and labels since they have to be of different lenghts and need
						# different padding methods
						lowerCAmelCase__		  =  [{'input_values': feature['input_values']} for feature in features]
						lowerCAmelCase__		  =  [{'input_ids': feature['labels']} for feature in features]

						lowerCAmelCase__		  =  self.processor.pad(
						    a_    ,padding=self.padding    ,max_length=self.max_length    ,pad_to_multiple_of=self.pad_to_multiple_of    ,return_tensors='pt'    ,)
						lowerCAmelCase__		  =  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
						lowerCAmelCase__		  =  labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1						)    ,-100						)

						lowerCAmelCase__		  =  labels

						return batch



class 	__snake_case   ( SCREAMING_SNAKE_CASE ):
		def 						SCREAMING_SNAKE_CASE_					(							self    ,a_    ,a_						):







						"""simple docstring"""
						model.train()
						lowerCAmelCase__		  =  self._prepare_inputs(a_						)

						if self.use_amp:
										with autocast():
														lowerCAmelCase__		  =  self.compute_loss(a_    ,a_						)
						else:
										lowerCAmelCase__		  =  self.compute_loss(a_    ,a_						)

						if self.args.n_gpu > 1:
										if model.module.config.ctc_loss_reduction == "mean":
														lowerCAmelCase__		  =  loss.mean()
										elif model.module.config.ctc_loss_reduction == "sum":
														lowerCAmelCase__		  =  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:
										lowerCAmelCase__		  =  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_		(					)	->     Optional[int]:



				"""simple docstring"""





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

				# Detecting last checkpoint.
				lowerCAmelCase__		  =  None
				if os.path.isdir(training_args.output_dir					) and training_args.do_train and not training_args.overwrite_output_dir:
								lowerCAmelCase__		  =  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:
				lowerCAmelCase__		  =  datasets.load_dataset(
				    'common_voice'    ,			data_args.dataset_config_name    ,			split=data_args.train_split_name					)
				lowerCAmelCase__		  =  datasets.load_dataset('common_voice'    ,			data_args.dataset_config_name    ,			split='test'					)

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

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

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

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

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

				lowerCAmelCase__		  =  list(set(vocab_train['vocab'][0]					) | set(vocab_test['vocab'][0]					)					)
				lowerCAmelCase__		  =  {v: k for k, v in enumerate(snake_case__					)}
				lowerCAmelCase__		  =  vocab_dict[' ']
				del vocab_dict[" "]
				lowerCAmelCase__		  =  len(snake_case__					)
				lowerCAmelCase__		  =  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.
				lowerCAmelCase__		  =  WavaVecaCTCTokenizer(
				    'vocab.json'    ,			unk_token='[UNK]'    ,			pad_token='[PAD]'    ,			word_delimiter_token='|'    ,			)
				lowerCAmelCase__		  =  WavaVecaFeatureExtractor(
				    feature_size=1    ,			sampling_rate=16000    ,			padding_value=0.0    ,			do_normalize=snake_case__    ,			return_attention_mask=snake_case__					)
				lowerCAmelCase__		  =  WavaVecaProcessor(feature_extractor=snake_case__    ,			tokenizer=snake_case__					)
				lowerCAmelCase__		  =  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:
								lowerCAmelCase__		  =  min(len(snake_case__					)    ,			data_args.max_train_samples					)
								lowerCAmelCase__		  =  train_dataset.select(range(snake_case__					)					)

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

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

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

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

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

				lowerCAmelCase__		  =  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    ,			)
				lowerCAmelCase__		  =  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
				lowerCAmelCase__		  =  datasets.load_metric('wer'					)

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

								lowerCAmelCase__		  =  processor.tokenizer.pad_token_id

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

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

								return {"wer": wer}

				if model_args.freeze_feature_extractor:
								model.freeze_feature_extractor()

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

				# Initialize our Trainer
				lowerCAmelCase__		  =  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:
												lowerCAmelCase__		  =  last_checkpoint
								elif os.path.isdir(model_args.model_name_or_path					):
												lowerCAmelCase__		  =  model_args.model_name_or_path
								else:
												lowerCAmelCase__		  =  None

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

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

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

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

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

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

				return results


if __name__ == "__main__":
	main()





import numpy as np







def     UpperCAmelCase_		(					snake_case__    ,			snake_case__    ,			snake_case__ = 1E-12    ,			snake_case__ = 100    ,			)	->     tuple[float, np.ndarray]:



				"""simple docstring"""





				assert np.shape(snake_case__					)[0] == np.shape(snake_case__					)[1]
				# Ensure proper dimensionality.
				assert np.shape(snake_case__					)[0] == np.shape(snake_case__					)[0]
				# Ensure inputs are either both complex or both real
				assert np.iscomplexobj(snake_case__					) == np.iscomplexobj(snake_case__					)
				lowerCAmelCase__		  =  np.iscomplexobj(snake_case__					)
				if is_complex:
								# Ensure complex input_matrix is Hermitian
								assert np.array_equal(snake_case__    ,			input_matrix.conj().T					)

				# Set convergence to False. Will define convergence when we exceed max_iterations
				# or when we have small changes from one iteration to next.

				lowerCAmelCase__		  =  False
				lowerCAmelCase__		  =  0
				lowerCAmelCase__		  =  0
				lowerCAmelCase__		  =  1E12

				while not convergence:
								# Multiple matrix by the vector.
								lowerCAmelCase__		  =  np.dot(snake_case__    ,			snake_case__					)
								# Normalize the resulting output vector.
								lowerCAmelCase__		  =  w / np.linalg.norm(snake_case__					)
								# Find rayleigh quotient
								# (faster than usual b/c we know vector is normalized already)
								lowerCAmelCase__		  =  vector.conj().T if is_complex else vector.T
								lowerCAmelCase__		  =  np.dot(snake_case__    ,			np.dot(snake_case__    ,			snake_case__					)					)

								# Check convergence.
								lowerCAmelCase__		  =  np.abs(lambda_ - lambda_previous					) / lambda_
								iterations += 1

								if error <= error_tol or iterations >= max_iterations:
												lowerCAmelCase__		  =  True

								lowerCAmelCase__		  =  lambda_

				if is_complex:
								lowerCAmelCase__		  =  np.real(lambda_					)

				return lambda_, vector







def     UpperCAmelCase_		(					)	->     None:



				"""simple docstring"""





				lowerCAmelCase__		  =  np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]]					)
				lowerCAmelCase__		  =  np.array([41, 4, 20]					)
				lowerCAmelCase__		  =  real_input_matrix.astype(np.complexaaa					)
				lowerCAmelCase__		  =  np.triu(1j * complex_input_matrix    ,			1					)
				complex_input_matrix += imag_matrix
				complex_input_matrix += -1 * imag_matrix.T
				lowerCAmelCase__		  =  np.array([41, 4, 20]					).astype(np.complexaaa					)

				for problem_type in ["real", "complex"]:
								if problem_type == "real":
												lowerCAmelCase__		  =  real_input_matrix
												lowerCAmelCase__		  =  real_vector
								elif problem_type == "complex":
												lowerCAmelCase__		  =  complex_input_matrix
												lowerCAmelCase__		  =  complex_vector

								# Our implementation.
								lowerCAmelCase__  ,   lowerCAmelCase__		  =  power_iteration(snake_case__    ,			snake_case__					)

								# Numpy implementation.

								# Get eigenvalues and eigenvectors using built-in numpy
								# eigh (eigh used for symmetric or hermetian matrices).
								lowerCAmelCase__  ,   lowerCAmelCase__		  =  np.linalg.eigh(snake_case__					)
								# Last eigenvalue is the maximum one.
								lowerCAmelCase__		  =  eigen_values[-1]
								# Last column in this matrix is eigenvector corresponding to largest eigenvalue.
								lowerCAmelCase__		  =  eigen_vectors[:, -1]

								# Check our implementation and numpy gives close answers.
								assert np.abs(eigen_value - eigen_value_max					) <= 1E-6
								# Take absolute values element wise of each eigenvector.
								# as they are only unique to a minus sign.
								assert np.linalg.norm(np.abs(snake_case__					) - np.abs(snake_case__					)					) <= 1E-6


if __name__ == "__main__":
	import doctest

	doctest.testmod()
	test_power_iteration()
