


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


_lowerCamelCase  =	logging.getLogger(__name__)


@dataclass
class       lowerCamelCase_		:





				"""simple docstring"""







				_lowerCAmelCase   :   str   				=       field(
				    metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} )
				_lowerCAmelCase   :   Optional[str]   				=       field(
				    default=lowercase							,	metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}							,	)
				_lowerCAmelCase   :   Optional[bool]   				=       field(
				    default=lowercase							,	metadata={"help": "Whether to freeze the feature extractor layers of the model."} )
				_lowerCAmelCase   :   Optional[bool]   				=       field(
				    default=lowercase							,	metadata={"help": "Whether to log verbose messages or not."}							,	)


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


@dataclass
class       lowerCamelCase_		:





				"""simple docstring"""







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


@dataclass
class       lowerCamelCase_		:





				"""simple docstring"""







				_lowerCAmelCase   :   bool   				=       False
				_lowerCAmelCase   :   Optional[str]   				=       None
				_lowerCAmelCase   :   Optional[str]   				=       "|"
				_lowerCAmelCase   :   Optional[Dict[str, str]]   				=       field(default_factory=lowercase )
				_lowerCAmelCase   :   Optional[Set[str]]   				=       field(default_factory=lowercase )
				_lowerCAmelCase   :   Optional[Callable[[str], str]]   				=       None



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



				def 	lowerCAmelCase__		(    self							,		UpperCAmelCase__  ):
								# TODO(elgeish) return a pipeline (e.g., from jiwer) instead? Or rely on branch predictor as is
								if len(self.translation_table  ) > 0:
												SCREAMING_SNAKE_CASE__  				=					text.translate(self.translation_table  )
								if len(self.words_to_remove  ) == 0:
												SCREAMING_SNAKE_CASE__  				=					" ".join(text.split()  )  # clean up whitespaces
								else:
												SCREAMING_SNAKE_CASE__  				=					" ".join(w for w in text.split() if w not in self.words_to_remove  )  # and clean up whilespaces
								return text






				def 	lowerCAmelCase__		(    self							,		UpperCAmelCase__  ):
								SCREAMING_SNAKE_CASE__  				=					WavaVecaFeatureExtractor.from_pretrained(
								    model_args.model_name_or_path							,		cache_dir=model_args.cache_dir  )
								if self.vocab_file:
												SCREAMING_SNAKE_CASE__  				=					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:
												SCREAMING_SNAKE_CASE__  				=					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(UpperCAmelCase__							,		UpperCAmelCase__  )


@dataclass
class       lowerCamelCase_		:





				"""simple docstring"""







				_lowerCAmelCase   :   WavaVecaProcessor
				_lowerCAmelCase   :   Union[bool, str]   				=       True
				_lowerCAmelCase   :   Optional[int]   				=       None
				_lowerCAmelCase   :   Optional[int]   				=       None
				_lowerCAmelCase   :   Optional[int]   				=       None
				_lowerCAmelCase   :   Optional[int]   				=       None



				def __call__(    self							,		UpperCAmelCase__  ):
								# split inputs and labels since they have to be of different lenghts and need
								# different padding methods
								SCREAMING_SNAKE_CASE__  				=					[{"input_values": feature["input_values"]} for feature in features]
								SCREAMING_SNAKE_CASE__  				=					[{"input_ids": feature["labels"]} for feature in features]

								SCREAMING_SNAKE_CASE__  				=					self.processor.pad(
								    UpperCAmelCase__							,		padding=self.padding							,		max_length=self.max_length							,		pad_to_multiple_of=self.pad_to_multiple_of							,		return_tensors="pt"							,		)
								SCREAMING_SNAKE_CASE__  				=					self.processor.pad(
								    labels=UpperCAmelCase__							,		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
								SCREAMING_SNAKE_CASE__  				=					labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1  )							,		-100  )

								SCREAMING_SNAKE_CASE__  				=					labels

								return batch


class       lowerCamelCase_		(      lowercase ):





				"""simple docstring"""







				def 	lowerCAmelCase__		(    self							,		UpperCAmelCase__							,		UpperCAmelCase__  ):
								model.train()
								SCREAMING_SNAKE_CASE__  				=					self._prepare_inputs(UpperCAmelCase__  )

								if self.use_amp:
												with autocast():
																SCREAMING_SNAKE_CASE__  				=					self.compute_loss(UpperCAmelCase__							,		UpperCAmelCase__  )
								else:
												SCREAMING_SNAKE_CASE__  				=					self.compute_loss(UpperCAmelCase__							,		UpperCAmelCase__  )

								if self.args.n_gpu > 1:
												if model.module.config.ctc_loss_reduction == "mean":
																SCREAMING_SNAKE_CASE__  				=					loss.mean()
												elif model.module.config.ctc_loss_reduction == "sum":
																SCREAMING_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:
												SCREAMING_SNAKE_CASE__  				=					loss / self.args.gradient_accumulation_steps

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

								return loss.detach()


def __lowercase  (   ):
				# 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.

				SCREAMING_SNAKE_CASE__  				=					HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)	)

				SCREAMING_SNAKE_CASE__				,   SCREAMING_SNAKE_CASE__				,   SCREAMING_SNAKE_CASE__  				=					parser.parse_args_into_dataclasses()
				configure_logger(lowerCamelCase_    ,       lowerCamelCase_	)

				SCREAMING_SNAKE_CASE__  				=					Orthography.from_name(data_args.orthography.lower()	)
				SCREAMING_SNAKE_CASE__  				=					orthography.create_processor(lowerCamelCase_	)
				SCREAMING_SNAKE_CASE__  				=					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	)    ,       )

				SCREAMING_SNAKE_CASE__  				=					datasets.load_dataset(
				    data_args.dataset_name    ,       data_args.dataset_config_name    ,       split=data_args.train_split_name	)
				SCREAMING_SNAKE_CASE__  				=					datasets.load_dataset(
				    data_args.dataset_name    ,       data_args.dataset_config_name    ,       split=data_args.validation_split_name	)

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

				def prepare_example(lowerCamelCase_	:   Dict	):  # TODO(elgeish) make use of multiprocessing?
								SCREAMING_SNAKE_CASE__				,   SCREAMING_SNAKE_CASE__  				=					librosa.load(example[data_args.speech_file_column]    ,       sr=lowerCamelCase_	)
								if data_args.max_duration_in_seconds is not None:
												SCREAMING_SNAKE_CASE__  				=					len(example["speech"]	) / example["sampling_rate"]
								# Normalize and clean up text; order matters!
								SCREAMING_SNAKE_CASE__  				=					orthography.preprocess_for_training(example[data_args.target_text_column]	)
								SCREAMING_SNAKE_CASE__  				=					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)	)
												SCREAMING_SNAKE_CASE__  				=					updated_text
								return example

				SCREAMING_SNAKE_CASE__  				=					train_dataset.map(lowerCamelCase_    ,       remove_columns=[data_args.speech_file_column]	)
				SCREAMING_SNAKE_CASE__  				=					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_	:   Tuple	):
												return example["duration_in_seconds"] <= data_args.max_duration_in_seconds

								SCREAMING_SNAKE_CASE__  				=					len(lowerCamelCase_	)
								SCREAMING_SNAKE_CASE__  				=					len(lowerCamelCase_	)
								SCREAMING_SNAKE_CASE__  				=					train_dataset.filter(lowerCamelCase_    ,       remove_columns=["duration_in_seconds"]	)
								SCREAMING_SNAKE_CASE__  				=					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}"'''	)
				SCREAMING_SNAKE_CASE__  				=					None

				def prepare_dataset(lowerCamelCase_	:   Tuple	):
								# 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}.'''

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

				SCREAMING_SNAKE_CASE__  				=					train_dataset.map(
				    lowerCamelCase_    ,       batch_size=training_args.per_device_train_batch_size    ,       batched=lowerCamelCase_    ,       num_proc=data_args.preprocessing_num_workers    ,       )
				SCREAMING_SNAKE_CASE__  				=					val_dataset.map(
				    lowerCamelCase_    ,       batch_size=training_args.per_device_train_batch_size    ,       batched=lowerCamelCase_    ,       num_proc=data_args.preprocessing_num_workers    ,       )

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

				def compute_metrics(lowerCamelCase_	:   Dict	):
								SCREAMING_SNAKE_CASE__  				=					pred.predictions
								SCREAMING_SNAKE_CASE__  				=					np.argmax(lowerCamelCase_    ,       axis=-1	)

								SCREAMING_SNAKE_CASE__  				=					processor.tokenizer.pad_token_id

								SCREAMING_SNAKE_CASE__  				=					processor.batch_decode(lowerCamelCase_	)
								# we do not want to group tokens when computing the metrics
								SCREAMING_SNAKE_CASE__  				=					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_	)}"'''	)

								SCREAMING_SNAKE_CASE__  				=					wer_metric.compute(predictions=lowerCamelCase_    ,       references=lowerCamelCase_	)

								return {"wer": wer}

				if model_args.freeze_feature_extractor:
								model.freeze_feature_extractor()

				SCREAMING_SNAKE_CASE__  				=					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"""






import torch

from transformers import AutoTokenizer


class       lowerCamelCase_		(      lowercase ):





				"""simple docstring"""







				def __init__(    self							,		UpperCAmelCase__  ):
								SCREAMING_SNAKE_CASE__  				=					AutoTokenizer.from_pretrained(UpperCAmelCase__  )



				def 	lowerCAmelCase__		(    self							,		UpperCAmelCase__  ):

								if isinstance(UpperCAmelCase__							,		UpperCAmelCase__  ) and all(isinstance(_x							,		UpperCAmelCase__  ) for _x in x  ):
												SCREAMING_SNAKE_CASE__  				=					None
												for l in x:
																SCREAMING_SNAKE_CASE__  				=					self.tokenizer(
																    UpperCAmelCase__							,		padding="max_length"							,		max_length=384							,		truncation=UpperCAmelCase__							,		return_tensors="pt"							,		)
																SCREAMING_SNAKE_CASE__  				=					torch.tensor([len(UpperCAmelCase__  )]  )
																if d is not None:
																				for k in d.keys():
																								SCREAMING_SNAKE_CASE__  				=					torch.cat((d[k], t[k])							,		0  )
																else:
																				SCREAMING_SNAKE_CASE__  				=					t

												SCREAMING_SNAKE_CASE__  				=					torch.tensor(self.tokenizer.convert_tokens_to_ids("[E]"  )  )
												SCREAMING_SNAKE_CASE__  				=					torch.tensor(self.tokenizer.convert_tokens_to_ids("[/E]"  )  )

								elif isinstance(UpperCAmelCase__							,		UpperCAmelCase__  ) and all(isinstance(_x							,		UpperCAmelCase__  ) for _x in x  ):
												SCREAMING_SNAKE_CASE__  				=					self.tokenizer(
												    UpperCAmelCase__							,		padding="max_length"							,		max_length=384							,		truncation=UpperCAmelCase__							,		return_tensors="pt"							,		)

								else:
												raise Exception(
												    "Type of parameter x was not recognized! Only `list of strings` for query or `list of lists of"
												    " strings` for supports are supported."  )

								return d






				def 	lowerCAmelCase__		(    self							,		UpperCAmelCase__							,		UpperCAmelCase__							,		UpperCAmelCase__							,		UpperCAmelCase__							,		UpperCAmelCase__=0.70  ):
								SCREAMING_SNAKE_CASE__  				=					[]
								for idx in range(len(W_query["input_ids"]  )  ):
												SCREAMING_SNAKE_CASE__  				=					SCREAMING_SNAKE_CASE__  				=					range(p_start.shape[1]  )

												SCREAMING_SNAKE_CASE__  				=					[]
												for start_id in start_indexes:
																for end_id in end_indexes:
																				if start_id < end_id:
																								output.append(
																								    (
																								        start_id,
																								        end_id,
																								        p_start[idx][start_id].item(),
																								        p_end[idx][end_id].item(),
																								    )  )

												output.sort(key=lambda UpperCAmelCase__  : (tup[2] * tup[3])							,		reverse=UpperCAmelCase__  )
												SCREAMING_SNAKE_CASE__  				=					[]
												for k in range(len(UpperCAmelCase__  )  ):
																if output[k][2] * output[k][3] >= thresh:
																				SCREAMING_SNAKE_CASE__				,   SCREAMING_SNAKE_CASE__  				=					output[k][0], output[k][1]
																				SCREAMING_SNAKE_CASE__  				=					self.tokenizer.decode(W_query["input_ids"][idx][c_start_pos:c_end_pos]  )
																				temp.append((decoded, output[k][2] * output[k][3])  )

												final_outputs.append(UpperCAmelCase__  )

								return final_outputs
