




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'):
							UpperCamelCase__						=		True
							from torch.cuda.amp import autocast


UpperCamelCase__						=		logging.getLogger(__name__)


@dataclass
class 							__SCREAMING_SNAKE_CASE				:
					_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=_UpperCAmelCase  ,	metadata={"""help""": """Whether to log verbose messages or not."""}  ,	)






def    snake_case   (				A		,  A     )				->				Optional[int]:




	'''simple docstring'''


	logging.basicConfig(
	    format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'		,  datefmt='%m/%d/%Y %H:%M:%S'		,  handlers=[logging.StreamHandler(sys.stdout     )]		,  )
	lowerCamelCase_				:						Optional[Any]				  =				logging.WARNING
	if model_args.verbose_logging:
		lowerCamelCase_				:						Optional[Any]				  =				logging.DEBUG
	elif trainer_utils.is_main_process(training_args.local_rank     ):
		lowerCamelCase_				:						Optional[int]				  =				logging.INFO
	logger.setLevel(SCREAMING_SNAKE_CASE__     )


@dataclass
class 							__SCREAMING_SNAKE_CASE				:
					_lowerCamelCase						    =					field(
					    default=_UpperCAmelCase  ,	metadata={"""help""": """The name of the dataset to use (via the datasets library)."""}    )
					_lowerCamelCase						    =					field(
					    default=_UpperCAmelCase  ,	metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""}    )
					_lowerCamelCase						    =					field(
					    default="""train"""  ,	metadata={
					        """help""": """The name of the training data set split to use (via the datasets library). Defaults to \'train\'"""
					    }  ,	)
					_lowerCamelCase						    =					field(
					    default="""validation"""  ,	metadata={
					        """help""": (
					            """The name of the validation data set split to use (via the datasets library). Defaults to \'validation\'"""
					        )
					    }  ,	)
					_lowerCamelCase						    =					field(
					    default="""text"""  ,	metadata={"""help""": """Column in the dataset that contains label (target text). Defaults to \'text\'"""}  ,	)
					_lowerCamelCase						    =					field(
					    default="""file"""  ,	metadata={"""help""": """Column in the dataset that contains speech file path. Defaults to \'file\'"""}  ,	)
					_lowerCamelCase						    =					field(
					    default=_UpperCAmelCase  ,	metadata={"""help""": """Resample loaded audio to target feature extractor\'s sampling rate or not."""}  ,	)
					_lowerCamelCase						    =					field(
					    default=_UpperCAmelCase  ,	metadata={"""help""": """Filters out examples longer than specified. Defaults to no filtering."""}  ,	)
					_lowerCamelCase						    =					field(
					    default="""librispeech"""  ,	metadata={
					        """help""": (
					            """Orthography used for normalization and tokenization: \'librispeech\' (default), \'timit\', or"""
					            """ \'buckwalter\'."""
					        )
					    }  ,	)
					_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."""}  ,	)


@dataclass
class 							__SCREAMING_SNAKE_CASE				:
					_lowerCamelCase						    =					False
					_lowerCamelCase						    =					None
					_lowerCamelCase						    =					"""|"""
					_lowerCamelCase						    =					field(default_factory=_UpperCAmelCase    )
					_lowerCamelCase						    =					field(default_factory=_UpperCAmelCase    )
					_lowerCamelCase						    =					None

					@classmethod
					def       lowercase_				(							cls					,			__lowercase   ):







						'''simple docstring'''




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

					def       lowercase_				(							self					,			__lowercase   ):







						'''simple docstring'''




						if len(self.translation_table   ) > 0:
							lowerCamelCase_				:						Any				  =				text.translate(self.translation_table   )
						if len(self.words_to_remove   ) == 0:
							lowerCamelCase_				:						List[str]				  =				' '.join(text.split()   )  # clean up whitespaces
						else:
							lowerCamelCase_				:						List[str]				  =				' '.join(w for w in text.split() if w not in self.words_to_remove   )  # and clean up whilespaces
						return text





					def       lowercase_				(							self					,			__lowercase   ):







						'''simple docstring'''




						lowerCamelCase_				:						Tuple				  =				WavaVecaFeatureExtractor.from_pretrained(
						    model_args.model_name_or_path					,			cache_dir=model_args.cache_dir   )
						if self.vocab_file:
							lowerCamelCase_				:						Optional[Any]				  =				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:
							lowerCamelCase_				:						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(lowercase_					,			lowercase_   )


@dataclass
class 							__SCREAMING_SNAKE_CASE				:
					_lowerCamelCase						    =					42
					_lowerCamelCase						    =					True
					_lowerCamelCase						    =					None
					_lowerCamelCase						    =					None
					_lowerCamelCase						    =					None
					_lowerCamelCase						    =					None

					def __call__(							self					,			__lowercase   ):







						'''simple docstring'''




						lowerCamelCase_				:						Tuple				  =				[{'input_values': feature['input_values']} for feature in features]
						lowerCamelCase_				:						Dict				  =				[{'input_ids': feature['labels']} for feature in features]

						lowerCamelCase_				:						int				  =				self.processor.pad(
						    lowercase_					,			padding=self.padding					,			max_length=self.max_length					,			pad_to_multiple_of=self.pad_to_multiple_of					,			return_tensors='pt'					,			)
						lowerCamelCase_				:						Optional[Any]				  =				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
						lowerCamelCase_				:						List[Any]				  =				labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1   )					,			-100   )

						lowerCamelCase_				:						Any				  =				labels

						return batch


class 							__SCREAMING_SNAKE_CASE				(						_UpperCAmelCase    ):

					def       lowercase_				(							self					,			__lowercase					,			__lowercase   ):







						'''simple docstring'''




						model.train()
						lowerCamelCase_				:						List[str]				  =				self._prepare_inputs(lowercase_   )

						if self.use_amp:
							with autocast():
								lowerCamelCase_				:						Optional[Any]				  =				self.compute_loss(lowercase_					,			lowercase_   )
						else:
							lowerCamelCase_				:						Union[str, Any]				  =				self.compute_loss(lowercase_					,			lowercase_   )

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




	'''simple docstring'''


	lowerCamelCase_				:						Union[str, Any]				  =				HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)     )

	lowerCamelCase_  ,     lowerCamelCase_  ,     lowerCamelCase_				:						Union[str, Any]				  =				parser.parse_args_into_dataclasses()
	configure_logger(SCREAMING_SNAKE_CASE__		,  SCREAMING_SNAKE_CASE__     )

	lowerCamelCase_				:						Dict				  =				Orthography.from_name(data_args.orthography.lower()     )
	lowerCamelCase_				:						List[str]				  =				orthography.create_processor(SCREAMING_SNAKE_CASE__     )
	lowerCamelCase_				:						List[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     )		,  )

	lowerCamelCase_				:						int				  =				datasets.load_dataset(
	    data_args.dataset_name		,  data_args.dataset_config_name		,  split=data_args.train_split_name     )
	lowerCamelCase_				:						str				  =				datasets.load_dataset(
	    data_args.dataset_name		,  data_args.dataset_config_name		,  split=data_args.validation_split_name     )

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

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

	lowerCamelCase_				:						Optional[int]				  =				train_dataset.map(SCREAMING_SNAKE_CASE__		,  remove_columns=[data_args.speech_file_column]     )
	lowerCamelCase_				:						Any				  =				val_dataset.map(SCREAMING_SNAKE_CASE__		,  remove_columns=[data_args.speech_file_column]     )

	if data_args.max_duration_in_seconds is not None:

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

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

	logger.warning(f"Updated {len(SCREAMING_SNAKE_CASE__     )} 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}\""     )
	lowerCamelCase_				:						Optional[Any]				  =				None

	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}."

		lowerCamelCase_				:						int				  =				processor(
		    audio=batch['speech']		,  text=batch[data_args.target_text_column]		,  sampling_rate=batch['sampling_rate'][0]     )
		batch.update(SCREAMING_SNAKE_CASE__     )
		return batch

	lowerCamelCase_				:						List[str]				  =				train_dataset.map(
	    SCREAMING_SNAKE_CASE__		,  batch_size=training_args.per_device_train_batch_size		,  batched=SCREAMING_SNAKE_CASE__		,  num_proc=data_args.preprocessing_num_workers		,  )
	lowerCamelCase_				:						Dict				  =				val_dataset.map(
	    SCREAMING_SNAKE_CASE__		,  batch_size=training_args.per_device_train_batch_size		,  batched=SCREAMING_SNAKE_CASE__		,  num_proc=data_args.preprocessing_num_workers		,  )

	lowerCamelCase_				:						Any				  =				DataCollatorCTCWithPadding(processor=SCREAMING_SNAKE_CASE__		,  padding=SCREAMING_SNAKE_CASE__     )

	def compute_metrics(A     ):
		lowerCamelCase_				:						Optional[Any]				  =				pred.predictions
		lowerCamelCase_				:						Optional[int]				  =				np.argmax(SCREAMING_SNAKE_CASE__		,  axis=-1     )

		lowerCamelCase_				:						str				  =				processor.tokenizer.pad_token_id

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

		lowerCamelCase_				:						List[str]				  =				wer_metric.compute(predictions=SCREAMING_SNAKE_CASE__		,  references=SCREAMING_SNAKE_CASE__     )

		return {"wer": wer}

	if model_args.freeze_feature_extractor:
		model.freeze_feature_extractor()

	lowerCamelCase_				:						Optional[int]				  =				CTCTrainer(
	    model=SCREAMING_SNAKE_CASE__		,  data_collator=SCREAMING_SNAKE_CASE__		,  args=SCREAMING_SNAKE_CASE__		,  compute_metrics=SCREAMING_SNAKE_CASE__		,  train_dataset=SCREAMING_SNAKE_CASE__		,  eval_dataset=SCREAMING_SNAKE_CASE__		,  tokenizer=processor.feature_extractor		,  )

	trainer.train()


if __name__ == "__main__":
							main()



from typing import List, Optional, Union

import numpy as np
import torch
import torchaudio.compliance.kaldi as ta_kaldi

from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import TensorType, logging


lowercase_									=    logging.get_logger(__name__)


class 					A		(				_UpperCAmelCase					):







    """simple docstring"""





    lowerCamelCase						      =				['input_values', 'attention_mask']


    def __init__( self					:			Tuple,lowercase_					:			Optional[Any]=1,lowercase_					:			Union[str, Any]=1_6_0_0_0,lowercase_					:			str=1_2_8,lowercase_					:			Optional[Any]=1_0_2_4,lowercase_					:			Union[str, Any]=0.0,lowercase_					:			Any=True,lowercase_					:			List[Any]=-4.2_677_393,lowercase_					:			Union[str, Any]=4.5_689_974,lowercase_					:			Dict=False,**lowercase_					:			Dict,)->       int:





        '''simple docstring'''







        super().__init__(feature_size=lowercase_,sampling_rate=lowercase_,padding_value=lowercase_,**lowercase_						)
        A__        =  num_mel_bins
        A__        =  max_length
        A__        =  do_normalize
        A__        =  mean
        A__        =  std
        A__        =  return_attention_mask


    def 		snake_case__	( self					:			Any,lowercase_					:			np.ndarray,lowercase_					:			int,)->       np.ndarray:





        '''simple docstring'''







        A__        =  torch.from_numpy(lowercase_						).unsqueeze(0						)
        A__        =  ta_kaldi.fbank(
            lowercase_,htk_compat=lowercase_,sample_frequency=self.sampling_rate,use_energy=lowercase_,window_type='hanning',num_mel_bins=self.num_mel_bins,dither=0.0,frame_shift=1_0,)

        A__        =  fbank.shape[0]
        A__        =  max_length - n_frames

        # pad or truncate, depending on difference
        if difference > 0:
            A__        =  torch.nn.ZeroPadad((0, 0, 0, difference)						)
            A__        =  pad_module(lowercase_						)
        elif difference < 0:
            A__        =  fbank[0:max_length, :]

        A__        =  fbank.numpy()

        return fbank


    def 		snake_case__	( self					:			int,lowercase_					:			np.ndarray						)->       np.ndarray:





        '''simple docstring'''







        return (input_values - (self.mean)) / (self.std * 2)


    def __call__( self					:			str,lowercase_					:			Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]],lowercase_					:			Optional[int] = None,lowercase_					:			Optional[Union[str, TensorType]] = None,**lowercase_					:			str,)->       BatchFeature:





        '''simple docstring'''







        if sampling_rate is not None:
            if sampling_rate != self.sampling_rate:
                raise ValueError(
                    F'The model corresponding to this feature extractor: {self} was trained using a sampling rate of'
                    F' {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with'
                    F' {self.sampling_rate} and not {sampling_rate}.'						)
        else:
            logger.warning(
                'It is strongly recommended to pass the `sampling_rate` argument to this function. '
                'Failing to do so can result in silent errors that might be hard to debug.'						)

        A__        =  isinstance(lowercase_,np.ndarray						) and len(raw_speech.shape						) > 1
        if is_batched_numpy and len(raw_speech.shape						) > 2:
            raise ValueError(F'Only mono-channel audio is supported for input to {self}'						)
        A__        =  is_batched_numpy or (
            isinstance(lowercase_,(list, tuple)						) and (isinstance(raw_speech[0],(np.ndarray, tuple, list)						))
        )

        if is_batched:
            A__        =  [np.asarray(lowercase_,dtype=np.floataa						) for speech in raw_speech]
        elif not is_batched and not isinstance(lowercase_,np.ndarray						):
            A__        =  np.asarray(lowercase_,dtype=np.floataa						)
        elif isinstance(lowercase_,np.ndarray						) and raw_speech.dtype is np.dtype(np.floataa						):
            A__        =  raw_speech.astype(np.floataa						)

        # always return batch
        if not is_batched:
            A__        =  [raw_speech]

        # extract fbank features and pad/truncate to max_length
        A__        =  [self._extract_fbank_features(lowercase_,max_length=self.max_length						) for waveform in raw_speech]

        # convert into BatchFeature
        A__        =  BatchFeature({'input_values': features}						)

        # make sure list is in array format
        A__        =  padded_inputs.get('input_values'						)
        if isinstance(input_values[0],lowercase_						):
            A__        =  [np.asarray(lowercase_,dtype=np.floataa						) for feature in input_values]

        # normalization
        if self.do_normalize:
            A__        =  [self.normalize(lowercase_						) for feature in input_values]

        if return_tensors is not None:
            A__        =  padded_inputs.convert_to_tensors(lowercase_						)

        return padded_inputs

