

"""simple docstring"""






import logging
import pathlib
import re
import sys
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional, Set, Union

import datasets
import librosa
import numpy as np
import torch
from lang_trans import arabic
from packaging import version
from torch import nn

from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaForCTC,
    WavaVecaProcessor,
    is_apex_available,
    trainer_utils,
)


if is_apex_available():
							from apex import amp

if version.parse(version.parse(torch.__version__).base_version) >= version.parse('''1.6'''):
							lowerCamelCase__			:					Dict							  =					True
							from torch.cuda.amp import autocast


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






@dataclass
class       _UpperCAmelCase     :
			__a	:    str			   =							field(
			    metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""})
			__a	:    Optional[str]			   =							field(
			    default=__a      ,       metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}      ,       )
			__a	:    Optional[bool]			   =							field(
			    default=__a      ,       metadata={"""help""": """Whether to freeze the feature extractor layers of the model."""})
			__a	:    Optional[bool]			   =							field(
			    default=__a      ,       metadata={"""help""": """Whether to log verbose messages or not."""}      ,       )
def  UpperCamelCase   (     _lowerCAmelCase       :  ModelArguments,					_lowerCAmelCase       :  TrainingArguments	)			->     Dict:
	logging.basicConfig(
	    format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""",					datefmt="""%m/%d/%Y %H:%M:%S""",					handlers=[logging.StreamHandler(sys.stdout	)],					)
	_UpperCAmelCase      :							List[Any]       =   logging.WARNING
	if model_args.verbose_logging:
		_UpperCAmelCase      :							Optional[Any]       =   logging.DEBUG
	elif trainer_utils.is_main_process(training_args.local_rank	):
		_UpperCAmelCase      :							Tuple       =   logging.INFO
	logger.setLevel(_lowerCAmelCase	)






@dataclass
class       _UpperCAmelCase     :
			__a	:    str			   =							field(
			    default=__a      ,       metadata={"""help""": """The name of the dataset to use (via the datasets library)."""})
			__a	:    Optional[str]			   =							field(
			    default=__a      ,       metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""})
			__a	:    Optional[str]			   =							field(
			    default="""train"""      ,       metadata={
			        """help""": """The name of the training data set split to use (via the datasets library). Defaults to 'train'"""
			    }      ,       )
			__a	:    Optional[str]			   =							field(
			    default="""validation"""      ,       metadata={
			        """help""": (
			            """The name of the validation data set split to use (via the datasets library). Defaults to 'validation'"""
			        )
			    }      ,       )
			__a	:    Optional[str]			   =							field(
			    default="""text"""      ,       metadata={"""help""": """Column in the dataset that contains label (target text). Defaults to 'text'"""}      ,       )
			__a	:    Optional[str]			   =							field(
			    default="""file"""      ,       metadata={"""help""": """Column in the dataset that contains speech file path. Defaults to 'file'"""}      ,       )
			__a	:    Optional[bool]			   =							field(
			    default=__a      ,       metadata={"""help""": """Resample loaded audio to target feature extractor's sampling rate or not."""}      ,       )
			__a	:    Optional[float]			   =							field(
			    default=__a      ,       metadata={"""help""": """Filters out examples longer than specified. Defaults to no filtering."""}      ,       )
			__a	:    Optional[str]			   =							field(
			    default="""librispeech"""      ,       metadata={
			        """help""": (
			            """Orthography used for normalization and tokenization: 'librispeech' (default), 'timit', or"""
			            """ 'buckwalter'."""
			        )
			    }      ,       )
			__a	:    bool			   =							field(
			    default=__a      ,       metadata={"""help""": """Overwrite the cached preprocessed datasets or not."""})
			__a	:    Optional[int]			   =							field(
			    default=__a      ,       metadata={"""help""": """The number of processes to use for the preprocessing."""}      ,       )






@dataclass
class       _UpperCAmelCase     :
			__a	:    bool			   =							False
			__a	:    Optional[str]			   =							None
			__a	:    Optional[str]			   =							"|"
			__a	:    Optional[Dict[str, str]]			   =							field(default_factory=__a)
			__a	:    Optional[Set[str]]			   =							field(default_factory=__a)
			__a	:    Optional[Callable[[str], str]]			   =							None
			@classmethod
			def 							__snake_case	(						cls ,						_A       )      ->      Union[str, Any]:






				'''simple docstring'''







				if name == "librispeech":
					return cls()
				if name == "timit":
					return cls(
					    do_lower_case=_A ,						translation_table=str.maketrans({"""-""": """ """}       ) ,						)
				if name == "buckwalter":
					_UpperCAmelCase      :							Union[str, Any]       =   {
					    """-""": """ """,  # sometimes used to represent pauses
					    """^""": """v""",  # fixing "tha" in arabic_speech_corpus dataset
					}
					return cls(
					    vocab_file=pathlib.Path(_A       ).parent.joinpath("""vocab/buckwalter.json"""       ) ,						word_delimiter_token="""/""" ,						translation_table=str.maketrans(_A       ) ,						words_to_remove={"""sil"""} ,						untransliterator=arabic.buckwalter.untransliterate ,						)
				raise ValueError(f'''Unsupported orthography: \'{name}\'.'''       )
			def 							__snake_case	(						self ,						_A       )      ->      str:






				'''simple docstring'''







				if len(self.translation_table       ) > 0:
					_UpperCAmelCase      :							int       =   text.translate(self.translation_table       )
				if len(self.words_to_remove       ) == 0:
					_UpperCAmelCase      :							int       =   """ """.join(text.split()       )  # clean up whitespaces
				else:
					_UpperCAmelCase      :							int       =   """ """.join(w for w in text.split() if w not in self.words_to_remove       )  # and clean up whilespaces
				return text
			def 							__snake_case	(						self ,						_A       )      ->      WavaVecaProcessor:






				'''simple docstring'''







				_UpperCAmelCase      :							str       =   WavaVecaFeatureExtractor.from_pretrained(
				    model_args.model_name_or_path ,						cache_dir=model_args.cache_dir       )
				if self.vocab_file:
					_UpperCAmelCase      :							int       =   WavaVecaCTCTokenizer(
					    self.vocab_file ,						cache_dir=model_args.cache_dir ,						do_lower_case=self.do_lower_case ,						word_delimiter_token=self.word_delimiter_token ,						)
				else:
					_UpperCAmelCase      :							Optional[Any]       =   WavaVecaCTCTokenizer.from_pretrained(
					    model_args.model_name_or_path ,						cache_dir=model_args.cache_dir ,						do_lower_case=self.do_lower_case ,						word_delimiter_token=self.word_delimiter_token ,						)
				return WavaVecaProcessor(_A ,						_A       )






@dataclass
class       _UpperCAmelCase     :
			__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 ,						_A       )      ->      Dict[str, torch.Tensor]:






				'''simple docstring'''







				_UpperCAmelCase      :							Optional[int]       =   [{"""input_values""": feature["""input_values"""]} for feature in features]
				_UpperCAmelCase      :							str       =   [{"""input_ids""": feature["""labels"""]} for feature in features]

				_UpperCAmelCase      :							int       =   self.processor.pad(
				    _A ,						padding=self.padding ,						max_length=self.max_length ,						pad_to_multiple_of=self.pad_to_multiple_of ,						return_tensors="""pt""" ,						)
				_UpperCAmelCase      :							Optional[Any]       =   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
				_UpperCAmelCase      :							int       =   labels_batch["""input_ids"""].masked_fill(labels_batch.attention_mask.ne(1       ) ,						-1_00       )

				_UpperCAmelCase      :							List[Any]       =   labels

				return batch






class       _UpperCAmelCase     (						__a):
			def 							__snake_case	(						self ,						_A ,						_A       )      ->      torch.Tensor:






				'''simple docstring'''







				model.train()
				_UpperCAmelCase      :							int       =   self._prepare_inputs(_A       )

				if self.use_amp:
					with autocast():
						_UpperCAmelCase      :							Optional[Any]       =   self.compute_loss(_A ,						_A       )
				else:
					_UpperCAmelCase      :							Optional[int]       =   self.compute_loss(_A ,						_A       )

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

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

				return loss.detach()
def  UpperCamelCase   (     )			->     List[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.

	_UpperCAmelCase      :							Optional[int]       =   HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)	)

	_UpperCAmelCase      :							Optional[int]       =   parser.parse_args_into_dataclasses()
	configure_logger(_lowerCAmelCase,					_lowerCAmelCase	)

	_UpperCAmelCase      :							Union[str, Any]       =   Orthography.from_name(data_args.orthography.lower()	)
	_UpperCAmelCase      :							Dict       =   orthography.create_processor(_lowerCAmelCase	)
	_UpperCAmelCase      :							Optional[Any]       =   WavaVecaForCTC.from_pretrained(
	    model_args.model_name_or_path,					cache_dir=model_args.cache_dir,					gradient_checkpointing=training_args.gradient_checkpointing,					vocab_size=len(processor.tokenizer	),					)

	_UpperCAmelCase      :							Any       =   datasets.load_dataset(
	    data_args.dataset_name,					data_args.dataset_config_name,					split=data_args.train_split_name	)
	_UpperCAmelCase      :							Optional[int]       =   datasets.load_dataset(
	    data_args.dataset_name,					data_args.dataset_config_name,					split=data_args.validation_split_name	)

	_UpperCAmelCase      :							Dict       =   datasets.load_metric("""wer"""	)
	_UpperCAmelCase      :							str       =   processor.feature_extractor.sampling_rate if data_args.target_feature_extractor_sampling_rate else None
	_UpperCAmelCase      :							List[str]       =   """""".join(t for t in processor.tokenizer.get_vocab().keys() if len(_lowerCAmelCase	) == 1	)
	_UpperCAmelCase      :							Optional[Any]       =   re.compile(  # remove characters not in vocabulary
	    Rf'''[^\s{re.escape(_lowerCAmelCase	)}]''',					flags=re.IGNORECASE if processor.tokenizer.do_lower_case else 0,					)
	_UpperCAmelCase      :							Optional[Any]       =   []

	def prepare_example(_lowerCAmelCase       :  List[Any]	):  # TODO(elgeish) make use of multiprocessing?
		_UpperCAmelCase      :							Optional[Any]       =   librosa.load(example[data_args.speech_file_column],					sr=_lowerCAmelCase	)
		if data_args.max_duration_in_seconds is not None:
			_UpperCAmelCase      :							Union[str, Any]       =   len(example["""speech"""]	) / example["""sampling_rate"""]
		# Normalize and clean up text; order matters!
		_UpperCAmelCase      :							int       =   orthography.preprocess_for_training(example[data_args.target_text_column]	)
		_UpperCAmelCase      :							str       =   vocabulary_text_cleaner.sub("""""",					_lowerCAmelCase	)
		if updated_text != example[data_args.target_text_column]:
			text_updates.append((example[data_args.target_text_column], updated_text)	)
			_UpperCAmelCase      :							int       =   updated_text
		return example

	_UpperCAmelCase      :							List[str]       =   train_dataset.map(_lowerCAmelCase,					remove_columns=[data_args.speech_file_column]	)
	_UpperCAmelCase      :							Tuple       =   val_dataset.map(_lowerCAmelCase,					remove_columns=[data_args.speech_file_column]	)

	if data_args.max_duration_in_seconds is not None:

		def filter_by_max_duration(_lowerCAmelCase       :  str	):
			return example["duration_in_seconds"] <= data_args.max_duration_in_seconds

		_UpperCAmelCase      :							Any       =   len(_lowerCAmelCase	)
		_UpperCAmelCase      :							str       =   len(_lowerCAmelCase	)
		_UpperCAmelCase      :							Any       =   train_dataset.filter(_lowerCAmelCase,					remove_columns=["""duration_in_seconds"""]	)
		_UpperCAmelCase      :							List[Any]       =   val_dataset.filter(_lowerCAmelCase,					remove_columns=["""duration_in_seconds"""]	)
		if len(_lowerCAmelCase	) > old_train_size:
			logger.warning(
			    f'''Filtered out {len(_lowerCAmelCase	) - old_train_size} train example(s) longer than'''
			    f''' {data_args.max_duration_in_seconds} second(s).'''	)
		if len(_lowerCAmelCase	) > old_val_size:
			logger.warning(
			    f'''Filtered out {len(_lowerCAmelCase	) - old_val_size} validation example(s) longer than'''
			    f''' {data_args.max_duration_in_seconds} second(s).'''	)
	logger.info(f'''Split sizes: {len(_lowerCAmelCase	)} train and {len(_lowerCAmelCase	)} validation.'''	)

	logger.warning(f'''Updated {len(_lowerCAmelCase	)} transcript(s) using \'{data_args.orthography}\' orthography rules.'''	)
	if logger.isEnabledFor(logging.DEBUG	):
		for original_text, updated_text in text_updates:
			logger.debug(f'''Updated text: "{original_text}" -> "{updated_text}"'''	)
	_UpperCAmelCase      :							Union[str, Any]       =   None

	def prepare_dataset(_lowerCAmelCase       :  List[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}.'''

		_UpperCAmelCase      :							List[str]       =   processor(
		    audio=batch["""speech"""],					text=batch[data_args.target_text_column],					sampling_rate=batch["""sampling_rate"""][0]	)
		batch.update(_lowerCAmelCase	)
		return batch

	_UpperCAmelCase      :							str       =   train_dataset.map(
	    _lowerCAmelCase,					batch_size=training_args.per_device_train_batch_size,					batched=_lowerCAmelCase,					num_proc=data_args.preprocessing_num_workers,					)
	_UpperCAmelCase      :							Tuple       =   val_dataset.map(
	    _lowerCAmelCase,					batch_size=training_args.per_device_train_batch_size,					batched=_lowerCAmelCase,					num_proc=data_args.preprocessing_num_workers,					)

	_UpperCAmelCase      :							Union[str, Any]       =   DataCollatorCTCWithPadding(processor=_lowerCAmelCase,					padding=_lowerCAmelCase	)

	def compute_metrics(_lowerCAmelCase       :  List[Any]	):
		_UpperCAmelCase      :							Union[str, Any]       =   pred.predictions
		_UpperCAmelCase      :							int       =   np.argmax(_lowerCAmelCase,					axis=-1	)

		_UpperCAmelCase      :							Optional[int]       =   processor.tokenizer.pad_token_id

		_UpperCAmelCase      :							List[str]       =   processor.batch_decode(_lowerCAmelCase	)
		# we do not want to group tokens when computing the metrics
		_UpperCAmelCase      :							int       =   processor.batch_decode(pred.label_ids,					group_tokens=_lowerCAmelCase	)
		if logger.isEnabledFor(logging.DEBUG	):
			for reference, predicted in zip(_lowerCAmelCase,					_lowerCAmelCase	):
				logger.debug(f'''reference: "{reference}"'''	)
				logger.debug(f'''predicted: "{predicted}"'''	)
				if orthography.untransliterator is not None:
					logger.debug(f'''reference (untransliterated): "{orthography.untransliterator(_lowerCAmelCase	)}"'''	)
					logger.debug(f'''predicted (untransliterated): "{orthography.untransliterator(_lowerCAmelCase	)}"'''	)

		_UpperCAmelCase      :							List[str]       =   wer_metric.compute(predictions=_lowerCAmelCase,					references=_lowerCAmelCase	)

		return {"wer": wer}

	if model_args.freeze_feature_extractor:
		model.freeze_feature_extractor()

	_UpperCAmelCase      :							List[str]       =   CTCTrainer(
	    model=_lowerCAmelCase,					data_collator=_lowerCAmelCase,					args=_lowerCAmelCase,					compute_metrics=_lowerCAmelCase,					train_dataset=_lowerCAmelCase,					eval_dataset=_lowerCAmelCase,					tokenizer=processor.feature_extractor,					)

	trainer.train()


if __name__ == "__main__":
							main()








"""simple docstring"""






from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_tf_available,
    is_torch_available,
)


lowerCamelCase__			:					Union[str, Any]							  =					{
    '''configuration_unispeech_sat''': ['''UNISPEECH_SAT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''UniSpeechSatConfig'''],
}

try:
						if not is_torch_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						lowerCamelCase__			:					List[str]							  =					[
						    '''UNISPEECH_SAT_PRETRAINED_MODEL_ARCHIVE_LIST''',
						    '''UniSpeechSatForAudioFrameClassification''',
						    '''UniSpeechSatForCTC''',
						    '''UniSpeechSatForPreTraining''',
						    '''UniSpeechSatForSequenceClassification''',
						    '''UniSpeechSatForXVector''',
						    '''UniSpeechSatModel''',
						    '''UniSpeechSatPreTrainedModel''',
						]

if TYPE_CHECKING:
						from .configuration_unispeech_sat import UNISPEECH_SAT_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechSatConfig

						try:
												if not is_torch_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .modeling_unispeech_sat import (
												    UNISPEECH_SAT_PRETRAINED_MODEL_ARCHIVE_LIST,
												    UniSpeechSatForAudioFrameClassification,
												    UniSpeechSatForCTC,
												    UniSpeechSatForPreTraining,
												    UniSpeechSatForSequenceClassification,
												    UniSpeechSatForXVector,
												    UniSpeechSatModel,
												    UniSpeechSatPreTrainedModel,
												)

else:
						import sys

						lowerCamelCase__			:					Any							  =					_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)





