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


__SCREAMING_SNAKE_CASE						:    Tuple     = logging.getLogger(__name__)



@dataclass
class    lowercase_    :
							_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						(__lowercase					,			__lowercase						)       ->       Dict:

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



@dataclass
class    lowercase_    :
							_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    lowercase_    :
							_lowerCamelCase						=		False
							_lowerCamelCase						=		None
							_lowerCamelCase						=		'|'
							_lowerCamelCase						=		field(default_factory=_UpperCamelCase		)
							_lowerCamelCase						=		field(default_factory=_UpperCamelCase		)
							_lowerCamelCase						=		None



							@classmethod
							def        UpperCamelCase       (						cls      ,				lowercase_				):







													if name == "librispeech":
																			return cls()
													if name == "timit":
																			return cls(
																			    do_lower_case=a__      ,				translation_table=str.maketrans({"-": " "}				)      ,				)
													if name == "buckwalter":
																			_snake_case						:     List[str]				=    {
																			    "-": " ",  # 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        UpperCamelCase       (						self      ,				lowercase_				):







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



							def        UpperCamelCase       (						self      ,				lowercase_				):
													_snake_case						:     List[Any]				=    WavaVecaFeatureExtractor.from_pretrained(
													    model_args.model_name_or_path      ,				cache_dir=model_args.cache_dir				)
													if self.vocab_file:
																			_snake_case						:     Union[str, 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:
																			_snake_case						:     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(a__      ,				a__				)




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



							def __call__(						self      ,				lowercase_				):
													_snake_case						:     Tuple				=    [{"input_values": feature["input_values"]} for feature in features]
													_snake_case						:     Union[str, Any]				=    [{"input_ids": feature["labels"]} for feature in features]

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

													_snake_case						:     int				=    labels

													return batch




class    lowercase_    (     _UpperCamelCase		):



							def        UpperCamelCase       (						self      ,				lowercase_      ,				lowercase_				):
													model.train()
													_snake_case						:     int				=    self._prepare_inputs(a__				)

													if self.use_amp:
																			with autocast():
																									_snake_case						:     List[str]				=    self.compute_loss(a__      ,				a__				)
													else:
																			_snake_case						:     Optional[int]				=    self.compute_loss(a__      ,				a__				)

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

						'''simple docstring'''



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

						_snake_case				,_snake_case				,_snake_case						:     str				=    parser.parse_args_into_dataclasses()
						configure_logger(__lowercase					,			__lowercase						)

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

						_snake_case						:     Union[str, Any]				=    datasets.load_dataset(
						    data_args.dataset_name					,			data_args.dataset_config_name					,			split=data_args.train_split_name						)
						_snake_case						:     Tuple				=    datasets.load_dataset(
						    data_args.dataset_name					,			data_args.dataset_config_name					,			split=data_args.validation_split_name						)

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

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

						_snake_case						:     Any				=    train_dataset.map(__lowercase					,			remove_columns=[data_args.speech_file_column]						)
						_snake_case						:     Any				=    val_dataset.map(__lowercase					,			remove_columns=[data_args.speech_file_column]						)

						if data_args.max_duration_in_seconds is not None:

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

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

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

						def prepare_dataset(__lowercase						):
												# 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						:     str				=    processor(
												    audio=batch["speech"]					,			text=batch[data_args.target_text_column]					,			sampling_rate=batch["sampling_rate"][0]						)
												batch.update(__lowercase						)
												return batch

						_snake_case						:     Union[str, Any]				=    train_dataset.map(
						    __lowercase					,			batch_size=training_args.per_device_train_batch_size					,			batched=__lowercase					,			num_proc=data_args.preprocessing_num_workers					,			)
						_snake_case						:     str				=    val_dataset.map(
						    __lowercase					,			batch_size=training_args.per_device_train_batch_size					,			batched=__lowercase					,			num_proc=data_args.preprocessing_num_workers					,			)

						_snake_case						:     str				=    DataCollatorCTCWithPadding(processor=__lowercase					,			padding=__lowercase						)

						def compute_metrics(__lowercase						):
												_snake_case						:     Optional[int]				=    pred.predictions
												_snake_case						:     Tuple				=    np.argmax(__lowercase					,			axis=-1						)

												_snake_case						:     Dict				=    processor.tokenizer.pad_token_id

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

												_snake_case						:     List[str]				=    wer_metric.compute(predictions=__lowercase					,			references=__lowercase						)

												return {"wer": wer}

						if model_args.freeze_feature_extractor:
												model.freeze_feature_extractor()

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

						trainer.train()


if __name__ == "__main__":
				main()



"""simple docstring"""


import warnings

from ...utils import logging
from .image_processing_mobilenet_va import MobileNetVaImageProcessor


a_											=			logging.get_logger(__name__)
class snake_case					(     _UpperCamelCase):







		def __init__(    self					:				str			,      *a__					:				Union[str, Any]			,      **a__					:				Optional[Any]						)				->  None:





						'''simple docstring'''







						warnings.warn(
						    "The class MobileNetV2FeatureExtractor is deprecated and will be removed in version 5 of Transformers."
						    " Please use MobileNetV2ImageProcessor instead."			,      a__			,      )
						super().__init__(*a__			,      **a__						)