
from ....configuration_utils import PretrainedConfig
from ....utils import logging


UpperCAmelCase	      = logging.get_logger(__name__)

UpperCAmelCase	      = {
    "Visual-Attention-Network/van-base": (
        "https://huggingface.co/Visual-Attention-Network/van-base/blob/main/config.json"
    ),
}







class        A_   (			UpperCAmelCase__   ):




	'''simple docstring'''


	_UpperCamelCase     :     Tuple							 =       """van"""





	def __init__(       self		,    snake_case=224		,    snake_case=3		,    snake_case=[7, 3, 3, 3]		,    snake_case=[4, 2, 2, 2]		,    snake_case=[64, 128, 320, 512]		,    snake_case=[3, 3, 12, 3]		,    snake_case=[8, 8, 4, 4]		,    snake_case="gelu"		,    snake_case=0.02		,    snake_case=1E-6		,    snake_case=1E-2		,    snake_case=0.0		,    snake_case=0.0		,    **snake_case		,    ):
		super().__init__(**__lowercase       )
		lowercase       =    image_size
		lowercase       =    num_channels
		lowercase       =    patch_sizes
		lowercase       =    strides
		lowercase       =    hidden_sizes
		lowercase       =    depths
		lowercase       =    mlp_ratios
		lowercase       =    hidden_act
		lowercase       =    initializer_range
		lowercase       =    layer_norm_eps
		lowercase       =    layer_scale_init_value
		lowercase       =    drop_path_rate
		lowercase       =    dropout_rate







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

lowercase__				:     List[Any] 		=						logging.getLogger(__name__)


def 						lowerCamelCase__    (		_A=None     ,	_A=None							):







	'''simple docstring'''





	return field(default_factory=lambda: default     ,	metadata=_A							)
@dataclass
class 		UpperCAmelCase   :







						'''simple docstring'''





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







@dataclass
class 		UpperCAmelCase   :







						'''simple docstring'''





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







@dataclass
class 		UpperCAmelCase   :







						'''simple docstring'''





						lowerCAmelCase_     		=   42
						lowerCAmelCase_     		=   True
						lowerCAmelCase_     		=   None
						lowerCAmelCase_     		=   None
						lowerCAmelCase_     		=   None
						lowerCAmelCase_     		=   None






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






							"""simple docstring"""






							snake_case_		    =     [{"input_values": feature["input_values"]} for feature in features]
							snake_case_		    =     [{"input_ids": feature["labels"]} for feature in features]

							snake_case_		    =     self.processor.pad(
							    __lowercase       ,	padding=self.padding       ,	max_length=self.max_length       ,	pad_to_multiple_of=self.pad_to_multiple_of       ,	return_tensors="pt"       ,	)
							snake_case_		    =     self.processor.pad(
							    labels=__lowercase       ,	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
							snake_case_		    =     labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1						)       ,	-1_00						)

							snake_case_		    =     labels

							return batch







class 		UpperCAmelCase   (				UpperCAmelCase__			):







						'''simple docstring'''





						def        snake_case__						(						self							:     str       ,	__lowercase							:     nn.Module       ,	__lowercase							:     Dict[str, Union[torch.Tensor, Any]]						):






							"""simple docstring"""






							model.train()
							snake_case_		    =     self._prepare_inputs(__lowercase						)

							if self.use_amp:
								with autocast():
									snake_case_		    =     self.compute_loss(__lowercase       ,	__lowercase						)
							else:
								snake_case_		    =     self.compute_loss(__lowercase       ,	__lowercase						)

							if self.args.n_gpu > 1:
								if model.module.config.ctc_loss_reduction == "mean":
									snake_case_		    =     loss.mean()
								elif model.module.config.ctc_loss_reduction == "sum":
									snake_case_		    =     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:
								snake_case_		    =     loss / self.args.gradient_accumulation_steps

							if self.use_amp:
								self.scaler.scale(__lowercase						).backward()
							elif self.use_apex:
								with amp.scale_loss(__lowercase       ,	self.optimizer						) as scaled_loss:
									scaled_loss.backward()
							elif self.deepspeed:
								self.deepspeed.backward(__lowercase						)
							else:
								loss.backward()

							return loss.detach()







def 						lowerCamelCase__    (		):







	'''simple docstring'''





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

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

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

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

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

	def remove_special_characters(_A							):
		snake_case_		    =     re.sub(_A     ,	""     ,	batch["sentence"]							).lower() + " "
		return batch

	snake_case_		    =     train_dataset.map(_A     ,	remove_columns=["sentence"]							)
	snake_case_		    =     eval_dataset.map(_A     ,	remove_columns=["sentence"]							)

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

	snake_case_		    =     train_dataset.map(
	    _A     ,	batched=_A     ,	batch_size=-1     ,	keep_in_memory=_A     ,	remove_columns=train_dataset.column_names     ,	)
	snake_case_		    =     train_dataset.map(
	    _A     ,	batched=_A     ,	batch_size=-1     ,	keep_in_memory=_A     ,	remove_columns=eval_dataset.column_names     ,	)

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

	with open("vocab.json"     ,	"w"							) as vocab_file:
		json.dump(_A     ,	_A							)

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

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

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

	snake_case_		    =     train_dataset.map(
	    _A     ,	remove_columns=train_dataset.column_names     ,	num_proc=data_args.preprocessing_num_workers     ,	)
	snake_case_		    =     eval_dataset.map(
	    _A     ,	remove_columns=eval_dataset.column_names     ,	num_proc=data_args.preprocessing_num_workers     ,	)

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

		snake_case_		    =     processor(
		    audio=batch["speech"]     ,	text=batch["target_text"]     ,	sampling_rate=batch["sampling_rate"][0]							)
		batch.update(_A							)
		return batch

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

	# Metric
	snake_case_		    =     datasets.load_metric("wer"							)

	def compute_metrics(_A							):
		snake_case_		    =     pred.predictions
		snake_case_		    =     np.argmax(_A     ,	axis=-1							)

		snake_case_		    =     processor.tokenizer.pad_token_id

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

		snake_case_		    =     wer_metric.compute(predictions=_A     ,	references=_A							)

		return {"wer": wer}

	if model_args.freeze_feature_extractor:
		model.freeze_feature_extractor()

	# Data collator
	snake_case_		    =     DataCollatorCTCWithPadding(processor=_A     ,	padding=_A							)

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

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

		snake_case_		    =     trainer.train(resume_from_checkpoint=_A							)
		trainer.save_model()

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

		trainer.log_metrics("train"     ,	_A							)
		trainer.save_metrics("train"     ,	_A							)
		trainer.save_state()

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

		trainer.log_metrics("eval"     ,	_A							)
		trainer.save_metrics("eval"     ,	_A							)

	return results


if __name__ == "__main__":
		main()
