




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


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


@dataclass
class  lowerCamelCase     :






			'''simple docstring'''





			UpperCamelCase__										=field(
			    metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''}    )
			UpperCamelCase__										=field(
			    default=_UpperCamelCase					,metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''}					,)
			UpperCamelCase__										=field(
			    default=_UpperCamelCase					,metadata={'''help''': '''Whether to freeze the feature extractor layers of the model.'''}    )
			UpperCamelCase__										=field(
			    default=_UpperCamelCase					,metadata={'''help''': '''Whether to log verbose messages or not.'''}					,)







def 		lowercase__ (		__A:						ModelArguments				,__A:						TrainingArguments					):





					'''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					)]				,)
					__magic_name__				:						Dict     				=				logging.WARNING
					if model_args.verbose_logging:
										__magic_name__				:						str     				=				logging.DEBUG
					elif trainer_utils.is_main_process(training_args.local_rank					):
										__magic_name__				:						Optional[int]     				=				logging.INFO
					logger.setLevel(__A					)


@dataclass
class  lowerCamelCase     :






			'''simple docstring'''





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






@dataclass
class  lowerCamelCase     :






			'''simple docstring'''





			UpperCamelCase__										=False
			UpperCamelCase__										=None
			UpperCamelCase__										="|"
			UpperCamelCase__										=field(default_factory=_UpperCamelCase    )
			UpperCamelCase__										=field(default_factory=_UpperCamelCase    )
			UpperCamelCase__										=None

			@classmethod
			def 				UpperCAmelCase__							(			cls      : int							,    lowerCamelCase_      : int	)    -> Optional[Any]:





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

			def 				UpperCAmelCase__							(			self      : Optional[int]							,    lowerCamelCase_      : Union[str, Any]	)    -> str:





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


			def 				UpperCAmelCase__							(			self      : Any							,    lowerCamelCase_      : Optional[int]	)    -> WavaVecaProcessor:
								__magic_name__				:						Optional[int]     				=				WavaVecaFeatureExtractor.from_pretrained(
								    model_args.model_name_or_path							,    cache_dir=model_args.cache_dir	)
								if self.vocab_file:
													__magic_name__				:						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:
													__magic_name__				:						int     				=				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(_SCREAMING_SNAKE_CASE							,    _SCREAMING_SNAKE_CASE	)






@dataclass
class  lowerCamelCase     :






			'''simple docstring'''





			UpperCamelCase__										=42
			UpperCamelCase__										=True
			UpperCamelCase__										=None
			UpperCamelCase__										=None
			UpperCamelCase__										=None
			UpperCamelCase__										=None

			def __call__(			self      : List[str]							,    lowerCamelCase_      : Optional[int]	)    -> Dict[str, torch.Tensor]:
								__magic_name__				:						List[Any]     				=				[{'''input_values''': feature['''input_values''']} for feature in features]
								__magic_name__				:						List[Any]     				=				[{'''input_ids''': feature['''labels''']} for feature in features]

								__magic_name__				:						Union[str, Any]     				=				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'''							,    )
								__magic_name__				:						List[str]     				=				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
								__magic_name__				:						List[Any]     				=				labels_batch['''input_ids'''].masked_fill(labels_batch.attention_mask.ne(1	)							,    -100	)

								__magic_name__				:						List[str]     				=				labels

								return batch






class  lowerCamelCase     (		_UpperCamelCase    ):






			'''simple docstring'''





			def 				UpperCAmelCase__							(			self      : List[Any]							,    lowerCamelCase_      : List[str]							,    lowerCamelCase_      : Optional[Any]	)    -> torch.Tensor:
								model.train()
								__magic_name__				:						List[Any]     				=				self._prepare_inputs(_SCREAMING_SNAKE_CASE	)

								if self.use_amp:
													with autocast():
																		__magic_name__				:						Tuple     				=				self.compute_loss(_SCREAMING_SNAKE_CASE							,    _SCREAMING_SNAKE_CASE	)
								else:
													__magic_name__				:						str     				=				self.compute_loss(_SCREAMING_SNAKE_CASE							,    _SCREAMING_SNAKE_CASE	)

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





					'''simple docstring'''






					__magic_name__				:						Dict     				=				HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)					)

					__magic_name__				,     __magic_name__				,     __magic_name__				:						List[str]     				=				parser.parse_args_into_dataclasses()
					configure_logger(__A				,__A					)

					__magic_name__				:						List[Any]     				=				Orthography.from_name(data_args.orthography.lower()					)
					__magic_name__				:						Any     				=				orthography.create_processor(__A					)
					__magic_name__				:						Union[str, 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					)				,)

					__magic_name__				:						List[str]     				=				datasets.load_dataset(
					    data_args.dataset_name				,data_args.dataset_config_name				,split=data_args.train_split_name					)
					__magic_name__				:						int     				=				datasets.load_dataset(
					    data_args.dataset_name				,data_args.dataset_config_name				,split=data_args.validation_split_name					)

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

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

					__magic_name__				:						List[Any]     				=				train_dataset.map(__A				,remove_columns=[data_args.speech_file_column]					)
					__magic_name__				:						Tuple     				=				val_dataset.map(__A				,remove_columns=[data_args.speech_file_column]					)

					if data_args.max_duration_in_seconds is not None:

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

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

					logger.warning(F'''Updated {len(__A					)} 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}\"'''					)
					__magic_name__				:						int     				=				None

					def prepare_dataset(__A:						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}.'''

										__magic_name__				:						Optional[Any]     				=				processor(
										    audio=batch['''speech''']				,text=batch[data_args.target_text_column]				,sampling_rate=batch['''sampling_rate'''][0]					)
										batch.update(__A					)
										return batch

					__magic_name__				:						Dict     				=				train_dataset.map(
					    __A				,batch_size=training_args.per_device_train_batch_size				,batched=__A				,num_proc=data_args.preprocessing_num_workers				,)
					__magic_name__				:						List[Any]     				=				val_dataset.map(
					    __A				,batch_size=training_args.per_device_train_batch_size				,batched=__A				,num_proc=data_args.preprocessing_num_workers				,)

					__magic_name__				:						Any     				=				DataCollatorCTCWithPadding(processor=__A				,padding=__A					)

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

										__magic_name__				:						str     				=				processor.tokenizer.pad_token_id

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

										__magic_name__				:						int     				=				wer_metric.compute(predictions=__A				,references=__A					)

										return {"wer": wer}

					if model_args.freeze_feature_extractor:
										model.freeze_feature_extractor()

					__magic_name__				:						Any     				=				CTCTrainer(
					    model=__A				,data_collator=__A				,args=__A				,compute_metrics=__A				,train_dataset=__A				,eval_dataset=__A				,tokenizer=processor.feature_extractor				,)

					trainer.train()


if __name__ == "__main__":
	main()











"""simple docstring"""



import warnings

from ...utils import logging
from .image_processing_vit import ViTImageProcessor


_snake_case							:   Tuple	  =       logging.get_logger(__name__)




class 							__lowercase(							_UpperCamelCase	):






						def __init__(       self     ,    *_SCREAMING_SNAKE_CASE     ,    **_SCREAMING_SNAKE_CASE)      ->	None:




											"""simple docstring"""





											warnings.warn(
											    'The class ViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please'
											    ' use ViTImageProcessor instead.'     ,    _SCREAMING_SNAKE_CASE     ,    )
											super().__init__(*_SCREAMING_SNAKE_CASE     ,    **_SCREAMING_SNAKE_CASE)