
import inspect
import math
import tempfile
import unittest

import numpy as np

from transformers import ViTMAEConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
				import torch
				from torch import nn

				from transformers import ViTMAEForPreTraining, ViTMAEModel
				from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
				from PIL import Image

				from transformers import ViTImageProcessor






class        SCREAMING_SNAKE_CASE__    :

							"""simple docstring"""






							def __init__(  self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_=13     ,	SCREAMING_SNAKE_CASE_=30     ,	SCREAMING_SNAKE_CASE_=2     ,	SCREAMING_SNAKE_CASE_=3     ,	SCREAMING_SNAKE_CASE_=True     ,	SCREAMING_SNAKE_CASE_=True     ,	SCREAMING_SNAKE_CASE_=32     ,	SCREAMING_SNAKE_CASE_=5     ,	SCREAMING_SNAKE_CASE_=4     ,	SCREAMING_SNAKE_CASE_=37     ,	SCREAMING_SNAKE_CASE_="gelu"     ,	SCREAMING_SNAKE_CASE_=0.1     ,	SCREAMING_SNAKE_CASE_=0.1     ,	SCREAMING_SNAKE_CASE_=10     ,	SCREAMING_SNAKE_CASE_=0.0_2     ,	SCREAMING_SNAKE_CASE_=3     ,	SCREAMING_SNAKE_CASE_=0.6     ,	SCREAMING_SNAKE_CASE_=None     ,	)->   Any:





													'''simple docstring'''






													__UpperCamelCase       =			parent
													__UpperCamelCase       =			batch_size
													__UpperCamelCase       =			image_size
													__UpperCamelCase       =			patch_size
													__UpperCamelCase       =			num_channels
													__UpperCamelCase       =			is_training
													__UpperCamelCase       =			use_labels
													__UpperCamelCase       =			hidden_size
													__UpperCamelCase       =			num_hidden_layers
													__UpperCamelCase       =			num_attention_heads
													__UpperCamelCase       =			intermediate_size
													__UpperCamelCase       =			hidden_act
													__UpperCamelCase       =			hidden_dropout_prob
													__UpperCamelCase       =			attention_probs_dropout_prob
													__UpperCamelCase       =			type_sequence_label_size
													__UpperCamelCase       =			initializer_range
													__UpperCamelCase       =			mask_ratio
													__UpperCamelCase       =			scope

													# in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above
													# (we add 1 for the [CLS] token)
													__UpperCamelCase       =			(image_size // patch_size) ** 2
													__UpperCamelCase       =			int(math.ceil((1 - mask_ratio) * (num_patches + 1)			)			)



							def     A__(  self			)->   Tuple:





													'''simple docstring'''






													__UpperCamelCase       =			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

													__UpperCamelCase       =			None
													if self.use_labels:
																			__UpperCamelCase       =			ids_tensor([self.batch_size]     ,	self.type_sequence_label_size			)

													__UpperCamelCase       =			self.get_config()

													return config, pixel_values, labels



							def     A__(  self			)->   str:





													'''simple docstring'''






													return ViTMAEConfig(
													    image_size=self.image_size     ,	patch_size=self.patch_size     ,	num_channels=self.num_channels     ,	hidden_size=self.hidden_size     ,	num_hidden_layers=self.num_hidden_layers     ,	num_attention_heads=self.num_attention_heads     ,	intermediate_size=self.intermediate_size     ,	hidden_act=self.hidden_act     ,	hidden_dropout_prob=self.hidden_dropout_prob     ,	attention_probs_dropout_prob=self.attention_probs_dropout_prob     ,	is_decoder=__A     ,	initializer_range=self.initializer_range     ,	mask_ratio=self.mask_ratio     ,	)



							def     A__(  self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_			)->   List[Any]:





													'''simple docstring'''






													__UpperCamelCase       =			ViTMAEModel(config=__A			)
													model.to(__A			)
													model.eval()
													__UpperCamelCase       =			model(__A			)
													self.parent.assertEqual(result.last_hidden_state.shape     ,	(self.batch_size, self.seq_length, self.hidden_size)			)



							def     A__(  self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_			)->   Optional[int]:





													'''simple docstring'''






													__UpperCamelCase       =			ViTMAEForPreTraining(__A			)
													model.to(__A			)
													model.eval()
													__UpperCamelCase       =			model(__A			)
													__UpperCamelCase       =			(self.image_size // self.patch_size) ** 2
													__UpperCamelCase       =			self.patch_size**2 * self.num_channels
													self.parent.assertEqual(result.logits.shape     ,	(self.batch_size, num_patches, expected_num_channels)			)

													# test greyscale images
													__UpperCamelCase       =			1
													__UpperCamelCase       =			ViTMAEForPreTraining(__A			)
													model.to(__A			)
													model.eval()
													__UpperCamelCase       =			floats_tensor([self.batch_size, 1, self.image_size, self.image_size]			)
													__UpperCamelCase       =			model(__A			)
													__UpperCamelCase       =			self.patch_size**2
													self.parent.assertEqual(result.logits.shape     ,	(self.batch_size, num_patches, expected_num_channels)			)



							def     A__(  self			)->   str:





													'''simple docstring'''






													__UpperCamelCase       =			self.prepare_config_and_inputs()
													__UpperCamelCase  ,							__UpperCamelCase  ,							__UpperCamelCase       =			config_and_inputs
													__UpperCamelCase       =			{'''pixel_values''': pixel_values}
													return config, inputs_dict






@require_torch
class        SCREAMING_SNAKE_CASE__    (							SCREAMING_SNAKE_CASE_   ,		SCREAMING_SNAKE_CASE_   ,		unittest.TestCase    ):

							"""simple docstring"""






							_snake_case     		=  (ViTMAEModel, ViTMAEForPreTraining) if is_torch_available() else ()
							_snake_case     		=  {'feature-extraction': ViTMAEModel} if is_torch_available() else {}

							_snake_case     		=  False
							_snake_case     		=  False
							_snake_case     		=  False
							_snake_case     		=  False



							def     A__(  self			)->   Union[str, Any]:





													'''simple docstring'''






													__UpperCamelCase       =			ViTMAEModelTester(self			)
													__UpperCamelCase       =			ConfigTester(self     ,	config_class=__A     ,	has_text_modality=__A     ,	hidden_size=37			)



							def     A__(  self			)->   str:





													'''simple docstring'''






													self.config_tester.run_common_tests()



							@unittest.skip(reason='''ViTMAE does not use inputs_embeds'''			)
							def     A__(  self			)->   int:





													'''simple docstring'''






													pass



							def     A__(  self			)->   Any:





													'''simple docstring'''






													__UpperCamelCase  ,							__UpperCamelCase       =			self.model_tester.prepare_config_and_inputs_for_common()

													for model_class in self.all_model_classes:
																			__UpperCamelCase       =			model_class(__A			)
																			self.assertIsInstance(model.get_input_embeddings()     ,	(nn.Module)			)
																			__UpperCamelCase       =			model.get_output_embeddings()
																			self.assertTrue(x is None or isinstance(__A     ,	nn.Linear			)			)



							def     A__(  self			)->   Dict:





													'''simple docstring'''






													__UpperCamelCase  ,							__UpperCamelCase       =			self.model_tester.prepare_config_and_inputs_for_common()

													for model_class in self.all_model_classes:
																			__UpperCamelCase       =			model_class(__A			)
																			__UpperCamelCase       =			inspect.signature(model.forward			)
																			# signature.parameters is an OrderedDict => so arg_names order is deterministic
																			__UpperCamelCase       =			[*signature.parameters.keys()]

																			__UpperCamelCase       =			['''pixel_values''']
																			self.assertListEqual(arg_names[:1]     ,	__A			)



							def     A__(  self			)->   Any:





													'''simple docstring'''






													__UpperCamelCase       =			self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_model(*__A			)



							def     A__(  self			)->   List[str]:





													'''simple docstring'''






													__UpperCamelCase       =			self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_pretraining(*__A			)



							def     A__(  self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_			)->   List[str]:





													'''simple docstring'''






													np.random.seed(2			)

													__UpperCamelCase       =			int((pt_model.config.image_size // pt_model.config.patch_size) ** 2			)
													__UpperCamelCase       =			np.random.uniform(size=(self.model_tester.batch_size, num_patches)			)
													__UpperCamelCase       =			torch.from_numpy(__A			)

													# Add `noise` argument.
													# PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument
													__UpperCamelCase       =			pt_noise

													super().check_pt_tf_models(__A     ,	__A     ,	__A			)



							def     A__(  self			)->   Dict:





													'''simple docstring'''






													__UpperCamelCase  ,							__UpperCamelCase       =			self.model_tester.prepare_config_and_inputs_for_common()

													for model_class in self.all_model_classes:
																			__UpperCamelCase       =			model_class(__A			)
																			model.to(__A			)
																			model.eval()
																			# make random mask reproducible
																			torch.manual_seed(2			)
																			with torch.no_grad():
																									__UpperCamelCase       =			model(**self._prepare_for_class(__A     ,	__A			)			)

																			__UpperCamelCase       =			outputs[0].cpu().numpy()
																			__UpperCamelCase       =			0

																			with tempfile.TemporaryDirectory() as tmpdirname:
																									model.save_pretrained(__A			)
																									__UpperCamelCase       =			model_class.from_pretrained(__A			)
																									model.to(__A			)
																									# make random mask reproducible
																									torch.manual_seed(2			)
																									with torch.no_grad():
																															__UpperCamelCase       =			model(**self._prepare_for_class(__A     ,	__A			)			)

																									# Make sure we don't have nans
																									__UpperCamelCase       =			after_outputs[0].cpu().numpy()
																									__UpperCamelCase       =			0
																									__UpperCamelCase       =			np.amax(np.abs(out_a - out_a			)			)
																									self.assertLessEqual(__A     ,	1E-5			)



							@unittest.skip(
							    reason='''ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load
    to get deterministic results.'''			)
							def     A__(  self			)->   int:





													'''simple docstring'''






													pass



							@unittest.skip(
							    reason='''ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load
    to get deterministic results.'''			)
							def     A__(  self			)->   List[str]:





													'''simple docstring'''






													pass



							@unittest.skip(
							    reason='''ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load
    to get deterministic results.'''			)
							def     A__(  self			)->   Optional[Any]:





													'''simple docstring'''






													pass



							@unittest.skip(reason='''ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load'''			)
							def     A__(  self			)->   Any:





													'''simple docstring'''






													pass



							@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''			)
							def     A__(  self			)->   Optional[int]:





													'''simple docstring'''






													pass



							@slow
							def     A__(  self			)->   Dict:





													'''simple docstring'''






													for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																			__UpperCamelCase       =			ViTMAEModel.from_pretrained(__A			)
																			self.assertIsNotNone(__A			)





def 	A_ (							)      ->    Dict:



						'''simple docstring'''

						__UpperCamelCase       =			Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
						return image






@require_torch
@require_vision
class        SCREAMING_SNAKE_CASE__    (							unittest.TestCase    ):

							"""simple docstring"""






							@cached_property
							def     A__(  self			)->   Any:





													'''simple docstring'''






													return ViTImageProcessor.from_pretrained('''facebook/vit-mae-base'''			) if is_vision_available() else None



							@slow
							def     A__(  self			)->   Union[str, Any]:





													'''simple docstring'''






													np.random.seed(2			)

													__UpperCamelCase       =			ViTMAEForPreTraining.from_pretrained('''facebook/vit-mae-base'''			).to(__A			)

													__UpperCamelCase       =			self.default_image_processor
													__UpperCamelCase       =			prepare_img()
													__UpperCamelCase       =			image_processor(images=__A     ,	return_tensors='''pt'''			).to(__A			)

													# prepare a noise vector that will be also used for testing the TF model
													# (this way we can ensure that the PT and TF models operate on the same inputs)
													__UpperCamelCase       =			ViTMAEConfig()
													__UpperCamelCase       =			int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2			)
													__UpperCamelCase       =			np.random.uniform(size=(1, num_patches)			)

													# forward pass
													with torch.no_grad():
																			__UpperCamelCase       =			model(**__A     ,	noise=torch.from_numpy(__A			).to(device=__A			)			)

													# verify the logits
													__UpperCamelCase       =			torch.Size((1, 196, 768)			)
													self.assertEqual(outputs.logits.shape     ,	__A			)

													__UpperCamelCase       =			torch.tensor(
													    [[-0.0_5_4_8, -1.7_0_2_3, -0.9_3_2_5], [0.3_7_2_1, -0.5_6_7_0, -0.2_2_3_3], [0.8_2_3_5, -1.3_8_7_8, -0.3_5_2_4]]			)

													self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]     ,	expected_slice.to(__A			)     ,	atol=1E-4			)			)






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__							:							int									=			True
				from torch.cuda.amp import autocast

lowercase__							:							Dict									=			logging.getLogger(__name__)




def 	A_ (							snake_case							:   List[str]=None ,      snake_case							:   int=None )      ->    List[str]:



						'''simple docstring'''

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






@dataclass
class        SCREAMING_SNAKE_CASE__    :

							"""simple docstring"""






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






@dataclass
class        SCREAMING_SNAKE_CASE__    :

							"""simple docstring"""






							_snake_case     		=  field(
							    default=SCREAMING_SNAKE_CASE_   ,		metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'}    )
							_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\''
							    }   ,		)
							_snake_case     		=  field(
							    default=SCREAMING_SNAKE_CASE_   ,		metadata={'help': 'Overwrite the cached preprocessed datasets or not.'}    )
							_snake_case     		=  field(
							    default=SCREAMING_SNAKE_CASE_   ,		metadata={'help': 'The number of processes to use for the preprocessing.'}   ,		)
							_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.'
							        )
							    }   ,		)
							_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.'
							        )
							    }   ,		)
							_snake_case     		=  list_field(
							    default=[',', '?', '.', '!', '-', ';', ':', '""', '%', '\'', '"', '�']   ,		metadata={'help': 'A list of characters to remove from the transcripts.'}   ,		)






@dataclass
class        SCREAMING_SNAKE_CASE__    :

							"""simple docstring"""






							_snake_case     		=  42
							_snake_case     		=  True
							_snake_case     		=  None
							_snake_case     		=  None
							_snake_case     		=  None
							_snake_case     		=  None



							def __call__(  self     ,	SCREAMING_SNAKE_CASE_			)->   Dict[str, torch.Tensor]:





													'''simple docstring'''






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

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

													__UpperCamelCase       =			labels

													return batch






class        SCREAMING_SNAKE_CASE__    (							SCREAMING_SNAKE_CASE_    ):

							"""simple docstring"""






							def     A__		(  self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_			)->   torch.Tensor:





													'''simple docstring'''






													model.train()
													__UpperCamelCase       =			self._prepare_inputs(SCREAMING_SNAKE_CASE_			)

													if self.use_amp:
																			with autocast():
																									__UpperCamelCase       =			self.compute_loss(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_			)
													else:
																			__UpperCamelCase       =			self.compute_loss(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_			)

													if self.args.n_gpu > 1:
																			if model.module.config.ctc_loss_reduction == "mean":
																									__UpperCamelCase       =			loss.mean()
																			elif model.module.config.ctc_loss_reduction == "sum":
																									__UpperCamelCase       =			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:
																			__UpperCamelCase       =			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 	A_ (							)      ->    Union[str, Any]:



						'''simple docstring'''

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

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

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

						def remove_special_characters(snake_case							:   Tuple ):
												__UpperCamelCase       =			re.sub(snake_case ,      '''''' ,      batch['''sentence'''] ).lower() + ''' '''
												return batch

						__UpperCamelCase       =			train_dataset.map(snake_case ,      remove_columns=['''sentence'''] )
						__UpperCamelCase       =			eval_dataset.map(snake_case ,      remove_columns=['''sentence'''] )

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

						__UpperCamelCase       =			train_dataset.map(
						    snake_case ,      batched=snake_case ,      batch_size=-1 ,      keep_in_memory=snake_case ,      remove_columns=train_dataset.column_names ,      )
						__UpperCamelCase       =			train_dataset.map(
						    snake_case ,      batched=snake_case ,      batch_size=-1 ,      keep_in_memory=snake_case ,      remove_columns=eval_dataset.column_names ,      )

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

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

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

						__UpperCamelCase       =			train_dataset.map(
						    snake_case ,      remove_columns=train_dataset.column_names ,      num_proc=data_args.preprocessing_num_workers ,      )
						__UpperCamelCase       =			eval_dataset.map(
						    snake_case ,      remove_columns=eval_dataset.column_names ,      num_proc=data_args.preprocessing_num_workers ,      )

						def prepare_dataset(snake_case							:   Optional[int] ):
												# 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}."

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

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

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

												__UpperCamelCase       =			processor.tokenizer.pad_token_id

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

												__UpperCamelCase       =			wer_metric.compute(predictions=snake_case ,      references=snake_case )

												return {"wer": wer}

						if model_args.freeze_feature_extractor:
												model.freeze_feature_extractor()

						# Data collator
						__UpperCamelCase       =			DataCollatorCTCWithPadding(processor=snake_case ,      padding=snake_case )

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

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

												__UpperCamelCase       =			trainer.train(resume_from_checkpoint=snake_case )
												trainer.save_model()

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

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

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

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

						return results


if __name__ == "__main__":
				main()




