"""simple docstring"""
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__					  =     True
					from torch.cuda.amp import autocast

SCREAMING_SNAKE_CASE__					  =     logging.getLogger(__name__)





def       lowerCAmelCase__			(	_UpperCamelCase				: List[str]=None       ,	_UpperCamelCase				: Union[str, Any]=None    )    -> Dict:





						"""simple docstring"""






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



@dataclass
class      lowerCAmelCase_			:



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





@dataclass
class      lowerCAmelCase_			:



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





@dataclass
class      lowerCAmelCase_			:



				"""simple docstring"""
				_lowerCAmelCase   :			Union[str, Any]	     =  42
				_lowerCAmelCase   :			Tuple	     =  True
				_lowerCAmelCase   :			Optional[int]	     =  None
				_lowerCAmelCase   :			Dict	     =  None
				_lowerCAmelCase   :			Optional[int]	     =  None
				_lowerCAmelCase   :			int	     =  None

				def __call__( self						,			lowerCAmelCase			):






										"""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(
										    _a						,			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=_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
										snake_case	    =	labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1			)						,			-1_00			)

										snake_case	    =	labels

										return batch





class      lowerCAmelCase_			(	lowerCAmelCase    ):



				"""simple docstring"""

				def 						snake_case       ( self						,			lowerCAmelCase						,			lowerCAmelCase			):






										"""simple docstring"""

										model.train()
										snake_case	    =	self._prepare_inputs(_a			)

										if self.use_amp:
																with autocast():
																						snake_case	    =	self.compute_loss(_a						,			_a			)
										else:
																snake_case	    =	self.compute_loss(_a						,			_a			)

										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(_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       lowerCAmelCase__			(	)    -> Optional[Any]:





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

						# 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(_UpperCamelCase				: Union[str, Any]    ):
												snake_case	    =	re.sub(_snake_case       ,	''       ,	batch['sentence']    ).lower() + " "
												return batch

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

						def extract_all_chars(_UpperCamelCase				: Union[str, Any]    ):
												snake_case	    =	" ".join(batch['text']    )
												snake_case	    =	list(set(_snake_case    )    )
												return {"vocab": [vocab], "all_text": [all_text]}

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

						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(4_8_0_0_0       ,	1_6_0_0_0    )

						# Preprocessing the datasets.
						# We need to read the aduio files as arrays and tokenize the targets.
						def speech_file_to_array_fn(_UpperCamelCase				: List[str]    ):
												snake_case	    =	torchaudio.load(batch['path']    )
												snake_case	    =	resampler(_snake_case    ).squeeze().numpy()
												snake_case	    =	1_6_0_0_0
												snake_case	    =	batch["text"]
												return batch

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

						def prepare_dataset(_UpperCamelCase				: Any    ):
												# 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(_snake_case    )
												return batch

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

						def compute_metrics(_UpperCamelCase				: List[Any]    ):
												snake_case	    =	pred.predictions
												snake_case	    =	np.argmax(_snake_case       ,	axis=-1    )

												snake_case	    =	processor.tokenizer.pad_token_id

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

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

												return {"wer": wer}

						if model_args.freeze_feature_extractor:
												model.freeze_feature_extractor()

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

						# Initialize our Trainer
						snake_case	    =	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:
																		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=_snake_case    )
												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(_snake_case    )
												)
												snake_case	    =	min(_snake_case       ,	len(_snake_case    )    )

												trainer.log_metrics('train'       ,	_snake_case    )
												trainer.save_metrics('train'       ,	_snake_case    )
												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(_snake_case    )
												snake_case	    =	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 importlib
import os

import fsspec
import pytest
from fsspec import register_implementation
from fsspec.registry import _registry as _fsspec_registry

from datasets.filesystems import COMPRESSION_FILESYSTEMS, HfFileSystem, extract_path_from_uri, is_remote_filesystem

from .utils import require_lza, require_zstandard






def   lowerCAmelCase_						(					_snake_case      :  List[Any]   )				->		List[Any]:







	'''simple docstring'''


	assert "mock" in _fsspec_registry
	assert "bz2" in _fsspec_registry






def   lowerCAmelCase_						(					)				->		Tuple:







	'''simple docstring'''


	assert "mock" not in _fsspec_registry
	assert "bz2" in _fsspec_registry






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







	'''simple docstring'''


	__magic_name__		:		Dict	   =     "mock-s3-bucket"
	__magic_name__		:		Any	   =     F'''s3://{mock_bucket}'''
	__magic_name__		:		str	   =     extract_path_from_uri(_snake_case   )
	assert dataset_path.startswith("s3://"   ) is False

	__magic_name__		:		Tuple	   =     "./local/path"
	__magic_name__		:		Optional[Any]	   =     extract_path_from_uri(_snake_case   )
	assert dataset_path == new_dataset_path






def   lowerCAmelCase_						(					_snake_case      :  List[str]   )				->		Optional[Any]:







	'''simple docstring'''


	__magic_name__		:		str	   =     is_remote_filesystem(_snake_case   )
	assert is_remote is True

	__magic_name__		:		Optional[int]	   =     fsspec.filesystem("file"   )

	__magic_name__		:		int	   =     is_remote_filesystem(_snake_case   )
	assert is_remote is False






@pytest.mark.parametrize("compression_fs_class"      ,   _snake_case   )
def   lowerCAmelCase_						(					_snake_case      :  Optional[int]      ,   _snake_case      :  Optional[Any]      ,   _snake_case      :  int      ,   _snake_case      :  Tuple      ,   _snake_case      :  Any      ,   _snake_case      :  Union[str, Any]      ,   _snake_case      :  Any   )				->		int:







	'''simple docstring'''


	__magic_name__		:		Any	   =     {"gzip": gz_file, "xz": xz_file, "zstd": zstd_file, "bz2": bza_file, "lz4": lza_file}
	__magic_name__		:		str	   =     input_paths[compression_fs_class.protocol]
	if input_path is None:
		__magic_name__		:		Dict	   =     F'''for \'{compression_fs_class.protocol}\' compression protocol, '''
		if compression_fs_class.protocol == "lz4":
			reason += require_lza.kwargs["reason"]
		elif compression_fs_class.protocol == "zstd":
			reason += require_zstandard.kwargs["reason"]
		pytest.skip(_snake_case   )
	__magic_name__		:		str	   =     fsspec.filesystem(compression_fs_class.protocol      ,   fo=_snake_case   )
	assert isinstance(_snake_case      ,   _snake_case   )
	__magic_name__		:		int	   =     os.path.basename(_snake_case   )
	__magic_name__		:		Optional[int]	   =     expected_filename[: expected_filename.rindex("."   )]
	assert fs.glob("*"   ) == [expected_filename]
	with fs.open(_snake_case      ,   "r"      ,   encoding="utf-8"   ) as f, open(_snake_case      ,   encoding="utf-8"   ) as expected_file:
		assert f.read() == expected_file.read()






@pytest.mark.parametrize("protocol"      ,   ["zip", "gzip"]   )
def   lowerCAmelCase_						(					_snake_case      :  List[Any]      ,   _snake_case      :  Optional[Any]      ,   _snake_case      :  Optional[Any]   )				->		str:







	'''simple docstring'''


	__magic_name__		:		int	   =     {"zip": zip_jsonl_path, "gzip": jsonl_gz_path}
	__magic_name__		:		int	   =     compressed_file_paths[protocol]
	__magic_name__		:		Tuple	   =     "dataset.jsonl"
	__magic_name__		:		List[str]	   =     F'''{protocol}://{member_file_path}::{compressed_file_path}'''
	__magic_name__   ,    *__magic_name__		:		Optional[Any]	   =     fsspec.get_fs_token_paths(_snake_case   )
	assert fs.isfile(_snake_case   )
	assert not fs.isfile("non_existing_" + member_file_path   )






@pytest.mark.integration
def   lowerCAmelCase_						(					_snake_case      :  Union[str, Any]      ,   _snake_case      :  Dict      ,   _snake_case      :  List[str]      ,   _snake_case      :  Tuple   )				->		str:







	'''simple docstring'''


	__magic_name__		:		int	   =     hf_api.dataset_info(_snake_case      ,   token=_snake_case   )
	__magic_name__		:		Optional[Any]	   =     HfFileSystem(repo_info=_snake_case      ,   token=_snake_case   )
	assert sorted(hffs.glob("*"   )   ) == [".gitattributes", "data"]
	assert hffs.isdir("data"   )
	assert hffs.isfile(".gitattributes"   ) and hffs.isfile("data/text_data.txt"   )
	with open(_snake_case   ) as f:
		assert hffs.open("data/text_data.txt"      ,   "r"   ).read() == f.read()






def   lowerCAmelCase_						(					)				->		Optional[int]:







	'''simple docstring'''


	__magic_name__		:		Optional[Any]	   =     "bz2"

	# Import module
	import datasets.filesystems

	# Overwrite protocol and reload
	register_implementation(_snake_case      ,   _snake_case      ,   clobber=_snake_case   )
	with pytest.warns(_snake_case   ) as warning_info:
		importlib.reload(datasets.filesystems   )

	assert len(_snake_case   ) == 1
	assert (
	    str(warning_info[0].message   )
	    == F'''A filesystem protocol was already set for {protocol} and will be overwritten.'''
	)
