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

SCREAMING_SNAKE_CASE__   :			List[str]												=    logging.getLogger(__name__)




def  __magic_name__ (   __lowerCAmelCase	:						Union[str, Any]=None		,  __lowerCAmelCase	:						Union[str, Any]=None							)			->   str:
				return field(default_factory=lambda: default		,  metadata=__lowerCAmelCase							)

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





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





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






		def __call__(		self		:							Union[str, Any]							,			SCREAMING_SNAKE_CASE__		:							List[Dict[str, Union[List[int], torch.Tensor]]]  )     ->							Dict[str, torch.Tensor]:
						# 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(
						    SCREAMING_SNAKE_CASE__							,			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=SCREAMING_SNAKE_CASE__							,			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  )							,			-1_00  )

						__lowerCamelCase    					=	labels

						return batch





class    lowerCAmelCase__     (	__lowercase			):






		def  __A       (		self		:							Dict							,			SCREAMING_SNAKE_CASE__		:							nn.Module							,			SCREAMING_SNAKE_CASE__		:							Dict[str, Union[torch.Tensor, Any]]  )     ->							torch.Tensor:
						model.train()
						__lowerCamelCase    					=	self._prepare_inputs(SCREAMING_SNAKE_CASE__  )

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

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

						return loss.detach()





def  __magic_name__ (   )			->   str:
				# 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.

				__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'''		,  __lowerCAmelCase							)

				# 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(__lowerCAmelCase	:						str							):
								__lowerCamelCase    					=	re.sub(__lowerCAmelCase		,  ''''''		,  batch['''sentence''']							).lower() + ''' '''
								return batch

				__lowerCamelCase    					=	train_dataset.map(__lowerCAmelCase		,  remove_columns=['''sentence''']							)
				__lowerCamelCase    					=	eval_dataset.map(__lowerCAmelCase		,  remove_columns=['''sentence''']							)

				def extract_all_chars(__lowerCAmelCase	:						Optional[int]							):
								__lowerCamelCase    					=	''' '''.join(batch['''text''']							)
								__lowerCamelCase    					=	list(set(__lowerCAmelCase							)							)
								return {"vocab": [vocab], "all_text": [all_text]}

				__lowerCamelCase    					=	train_dataset.map(
				    __lowerCAmelCase		,  batched=__lowerCAmelCase		,  batch_size=-1		,  keep_in_memory=__lowerCAmelCase		,  remove_columns=train_dataset.column_names		,  )
				__lowerCamelCase    					=	train_dataset.map(
				    __lowerCAmelCase		,  batched=__lowerCAmelCase		,  batch_size=-1		,  keep_in_memory=__lowerCAmelCase		,  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(__lowerCAmelCase							)}
				__lowerCamelCase    					=	vocab_dict[''' ''']
				del vocab_dict[" "]
				__lowerCamelCase    					=	len(__lowerCAmelCase							)
				__lowerCamelCase    					=	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.
				__lowerCamelCase    					=	WavaVecaCTCTokenizer(
				    '''vocab.json'''		,  unk_token='''[UNK]'''		,  pad_token='''[PAD]'''		,  word_delimiter_token='''|'''		,  )
				__lowerCamelCase    					=	WavaVecaFeatureExtractor(
				    feature_size=1		,  sampling_rate=1_6000		,  padding_value=0.0		,  do_normalize=__lowerCAmelCase		,  return_attention_mask=__lowerCAmelCase							)
				__lowerCamelCase    					=	WavaVecaProcessor(feature_extractor=__lowerCAmelCase		,  tokenizer=__lowerCAmelCase							)
				__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(__lowerCAmelCase							)		,  data_args.max_train_samples							)
								__lowerCamelCase    					=	train_dataset.select(range(__lowerCAmelCase							)							)

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

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

				__lowerCamelCase    					=	train_dataset.map(
				    __lowerCAmelCase		,  remove_columns=train_dataset.column_names		,  num_proc=data_args.preprocessing_num_workers		,  )
				__lowerCamelCase    					=	eval_dataset.map(
				    __lowerCAmelCase		,  remove_columns=eval_dataset.column_names		,  num_proc=data_args.preprocessing_num_workers		,  )

				def prepare_dataset(__lowerCAmelCase	:						str							):
								# 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(__lowerCAmelCase							)
								return batch

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

				def compute_metrics(__lowerCAmelCase	:						int							):
								__lowerCamelCase    					=	pred.predictions
								__lowerCamelCase    					=	np.argmax(__lowerCAmelCase		,  axis=-1							)

								__lowerCamelCase    					=	processor.tokenizer.pad_token_id

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

								__lowerCamelCase    					=	wer_metric.compute(predictions=__lowerCAmelCase		,  references=__lowerCAmelCase							)

								return {"wer": wer}

				if model_args.freeze_feature_extractor:
								model.freeze_feature_extractor()

				# Data collator
				__lowerCamelCase    					=	DataCollatorCTCWithPadding(processor=__lowerCAmelCase		,  padding=__lowerCAmelCase							)

				# Initialize our Trainer
				__lowerCamelCase    					=	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:
												__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=__lowerCAmelCase							)
								trainer.save_model()

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

								trainer.log_metrics('''train'''		,  __lowerCAmelCase							)
								trainer.save_metrics('''train'''		,  __lowerCAmelCase							)
								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(__lowerCAmelCase							)
								__lowerCamelCase    					=	min(__lowerCAmelCase		,  len(__lowerCAmelCase							)							)

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

				return results


if __name__ == "__main__":
					main()





from abc import ABC, abstractmethod
from argparse import ArgumentParser

class    lowerCAmelCase__     (	__lowercase			):






		@staticmethod
		@abstractmethod
		def  __A       (		SCREAMING_SNAKE_CASE__		:							ArgumentParser  )     ->							str:
						raise NotImplementedError()







		@abstractmethod
		def  __A       (		self		:							Optional[int]  )     ->							Union[str, Any]:
						raise NotImplementedError()



