

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


__A		     =    logging.getLogger(__name__)





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






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





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





@dataclass
class 					snake_case			:
				SCREAMING_SNAKE_CASE_     :   bool        =						False
				SCREAMING_SNAKE_CASE_     :   Optional[str]        =						None
				SCREAMING_SNAKE_CASE_     :   Optional[str]        =						"|"
				SCREAMING_SNAKE_CASE_     :   Optional[Dict[str, str]]        =						field(default_factory=__snake_case						)
				SCREAMING_SNAKE_CASE_     :   Optional[Set[str]]        =						field(default_factory=__snake_case						)
				SCREAMING_SNAKE_CASE_     :   Optional[Callable[[str], str]]        =						None

				@classmethod
				def 							lowercase_  (			cls							:       List[str]  ,						UpperCamelCase__							:       str)->     List[str]:



						'''simple docstring'''


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



						'''simple docstring'''


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




				def 							lowercase_  (			self							:       int  ,						UpperCamelCase__							:       ModelArguments)->     WavaVecaProcessor:



						'''simple docstring'''


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





@dataclass
class 					snake_case			:
				SCREAMING_SNAKE_CASE_     :   WavaVecaProcessor
				SCREAMING_SNAKE_CASE_     :   Union[bool, str]        =						True
				SCREAMING_SNAKE_CASE_     :   Optional[int]        =						None
				SCREAMING_SNAKE_CASE_     :   Optional[int]        =						None
				SCREAMING_SNAKE_CASE_     :   Optional[int]        =						None
				SCREAMING_SNAKE_CASE_     :   Optional[int]        =						None

				def __call__(			self							:       Tuple  ,						UpperCamelCase__							:       List[Dict[str, Union[List[int], torch.Tensor]]])->     Dict[str, torch.Tensor]:



						'''simple docstring'''


						__lowerCAmelCase: str					   =    [{"input_values": feature["input_values"]} for feature in features]
						__lowerCAmelCase: str					   =    [{"input_ids": feature["labels"]} for feature in features]

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

						__lowerCAmelCase: Dict					   =    labels

						return batch





class 					snake_case			(       __snake_case						):

				def 							lowercase_  (			self							:       int  ,						UpperCamelCase__							:       nn.Module  ,						UpperCamelCase__							:       Dict[str, Union[torch.Tensor, Any]])->     torch.Tensor:



						'''simple docstring'''


						model.train()
						__lowerCAmelCase: str					   =    self._prepare_inputs(UpperCamelCase__)

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

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

		__lowerCAmelCase: Tuple					   =    HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)				)

		__lowerCAmelCase   ,				__lowerCAmelCase   ,				__lowerCAmelCase: Any					   =    parser.parse_args_into_dataclasses()
		configure_logger(__SCREAMING_SNAKE_CASE      ,				__SCREAMING_SNAKE_CASE				)

		__lowerCAmelCase: Tuple					   =    Orthography.from_name(data_args.orthography.lower()				)
		__lowerCAmelCase: int					   =    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: Tuple					   =    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: int					   =    "".join(t for t in processor.tokenizer.get_vocab().keys() if len(__SCREAMING_SNAKE_CASE				) == 1				)
		__lowerCAmelCase: str					   =    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: Any					   =    []

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

		__lowerCAmelCase: Optional[int]					   =    train_dataset.map(__SCREAMING_SNAKE_CASE      ,				remove_columns=[data_args.speech_file_column]				)
		__lowerCAmelCase: Optional[int]					   =    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(__SCREAMING_SNAKE_CASE				):
						return example["duration_in_seconds"] <= data_args.max_duration_in_seconds

				__lowerCAmelCase: List[str]					   =    len(__SCREAMING_SNAKE_CASE				)
				__lowerCAmelCase: Dict					   =    len(__SCREAMING_SNAKE_CASE				)
				__lowerCAmelCase: Tuple					   =    train_dataset.filter(__SCREAMING_SNAKE_CASE      ,				remove_columns=["duration_in_seconds"]				)
				__lowerCAmelCase: Any					   =    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[int]					   =    None

		def prepare_dataset(__SCREAMING_SNAKE_CASE				):
				# 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: str					   =    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: Optional[int]					   =    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: Union[str, Any]					   =    DataCollatorCTCWithPadding(processor=__SCREAMING_SNAKE_CASE      ,				padding=__SCREAMING_SNAKE_CASE				)

		def compute_metrics(__SCREAMING_SNAKE_CASE				):
				__lowerCAmelCase: List[str]					   =    pred.predictions
				__lowerCAmelCase: str					   =    np.argmax(__SCREAMING_SNAKE_CASE      ,				axis=-1				)

				__lowerCAmelCase: int					   =    processor.tokenizer.pad_token_id

				__lowerCAmelCase: Dict					   =    processor.batch_decode(__SCREAMING_SNAKE_CASE				)
				# we do not want to group tokens when computing the metrics
				__lowerCAmelCase: Dict					   =    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: Dict					   =    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: Dict					   =    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()





"""simple docstring"""


def 					a__					(					__SCREAMING_SNAKE_CASE = 1_0_0_0				)			->			int:
		__lowerCAmelCase: int					   =    0
		__lowerCAmelCase: Optional[int]					   =    0
		while 1:
				num += 3
				if num >= n:
						break
				total += num
				num += 2
				if num >= n:
						break
				total += num
				num += 1
				if num >= n:
						break
				total += num
				num += 3
				if num >= n:
						break
				total += num
				num += 1
				if num >= n:
						break
				total += num
				num += 2
				if num >= n:
						break
				total += num
				num += 3
				if num >= n:
						break
				total += num
		return total


if __name__ == "__main__":
			print(F'''{solution() = }''')


