





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


A :			Union[str, Any]							   =      logging.getLogger(__name__)







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





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







@dataclass
class       lowerCamelCase       :
					_SCREAMING_SNAKE_CASE				 =     field(
					    default=__UpperCAmelCase  ,				metadata={"help": "The name of the dataset to use (via the datasets library)."}	)
					_SCREAMING_SNAKE_CASE				 =     field(
					    default=__UpperCAmelCase  ,				metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}	)
					_SCREAMING_SNAKE_CASE				 =     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				 =     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				 =     field(
					    default="text"  ,				metadata={"help": "Column in the dataset that contains label (target text). Defaults to 'text'"}  ,				)
					_SCREAMING_SNAKE_CASE				 =     field(
					    default="file"  ,				metadata={"help": "Column in the dataset that contains speech file path. Defaults to 'file'"}  ,				)
					_SCREAMING_SNAKE_CASE				 =     field(
					    default=__UpperCAmelCase  ,				metadata={"help": "Resample loaded audio to target feature extractor's sampling rate or not."}  ,				)
					_SCREAMING_SNAKE_CASE				 =     field(
					    default=__UpperCAmelCase  ,				metadata={"help": "Filters out examples longer than specified. Defaults to no filtering."}  ,				)
					_SCREAMING_SNAKE_CASE				 =     field(
					    default="librispeech"  ,				metadata={
					        "help": (
					            "Orthography used for normalization and tokenization: 'librispeech' (default), 'timit', or"
					            " 'buckwalter'."
					        )
					    }  ,				)
					_SCREAMING_SNAKE_CASE				 =     field(
					    default=__UpperCAmelCase  ,				metadata={"help": "Overwrite the cached preprocessed datasets or not."}	)
					_SCREAMING_SNAKE_CASE				 =     field(
					    default=__UpperCAmelCase  ,				metadata={"help": "The number of processes to use for the preprocessing."}  ,				)







@dataclass
class       lowerCamelCase       :
					_SCREAMING_SNAKE_CASE				 =     False
					_SCREAMING_SNAKE_CASE				 =     None
					_SCREAMING_SNAKE_CASE				 =     "|"
					_SCREAMING_SNAKE_CASE				 =     field(default_factory=__UpperCAmelCase	)
					_SCREAMING_SNAKE_CASE				 =     field(default_factory=__UpperCAmelCase	)
					_SCREAMING_SNAKE_CASE				 =     None


					@classmethod
					def  SCREAMING_SNAKE_CASE_		(       cls						:	Union[str, Any]							,  __snake_case						:	str							):





											'''simple docstring'''





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


					def  SCREAMING_SNAKE_CASE_		(       self						:	str							,  __snake_case						:	str							):





											'''simple docstring'''





											if len(self.translation_table							) > 0:
																	_snake_case: Dict	       =		text.translate(self.translation_table							)
											if len(self.words_to_remove							) == 0:
																	_snake_case: List[str]	       =		' '.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  SCREAMING_SNAKE_CASE_		(       self						:	Optional[Any]							,  __snake_case						:	ModelArguments							):





											'''simple docstring'''





											_snake_case: 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: Dict	       =		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(__snake_case							,  __snake_case							)







@dataclass
class       lowerCamelCase       :
					_SCREAMING_SNAKE_CASE				 =     42
					_SCREAMING_SNAKE_CASE				 =     True
					_SCREAMING_SNAKE_CASE				 =     None
					_SCREAMING_SNAKE_CASE				 =     None
					_SCREAMING_SNAKE_CASE				 =     None
					_SCREAMING_SNAKE_CASE				 =     None


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





											'''simple docstring'''





											_snake_case: Any	       =		[{'input_values': feature['input_values']} for feature in features]
											_snake_case: Any	       =		[{'input_ids': feature['labels']} for feature in features]

											_snake_case: str	       =		self.processor.pad(
											    __snake_case							,  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=__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
											_snake_case: Optional[int]	       =		labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1							)							,  -1_00							)

											_snake_case: str	       =		labels

											return batch







class       lowerCamelCase       (    __UpperCAmelCase	):


					def  SCREAMING_SNAKE_CASE_		(       self						:	int							,  __snake_case						:	nn.Module							,  __snake_case						:	Dict[str, Union[torch.Tensor, Any]]							):





											'''simple docstring'''





											model.train()
											_snake_case: Optional[int]	       =		self._prepare_inputs(__snake_case							)

											if self.use_amp:
																	with autocast():
																							_snake_case: int	       =		self.compute_loss(__snake_case							,  __snake_case							)
											else:
																	_snake_case: Dict	       =		self.compute_loss(__snake_case							,  __snake_case							)

											if self.args.n_gpu > 1:
																	if model.module.config.ctc_loss_reduction == "mean":
																							_snake_case: List[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: int	       =		loss / self.args.gradient_accumulation_steps

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

											return loss.detach()





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

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

						_snake_case       ,    _snake_case       ,    _snake_case: Tuple	       =		parser.parse_args_into_dataclasses()
						configure_logger(lowercase__					,	lowercase__    )

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

						_snake_case: 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: Optional[int]	       =		datasets.load_metric('wer'    )
						_snake_case: List[Any]	       =		processor.feature_extractor.sampling_rate if data_args.target_feature_extractor_sampling_rate else None
						_snake_case: int	       =		''.join(t for t in processor.tokenizer.get_vocab().keys() if len(lowercase__    ) == 1    )
						_snake_case: Optional[int]	       =		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: int	       =		librosa.load(example[data_args.speech_file_column]					,	sr=lowercase__    )
												if data_args.max_duration_in_seconds is not None:
																		_snake_case: List[str]	       =		len(example['speech']    ) / example['sampling_rate']
												# Normalize and clean up text; order matters!
												_snake_case: Optional[Any]	       =		orthography.preprocess_for_training(example[data_args.target_text_column]    )
												_snake_case: Tuple	       =		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[Any]	       =		updated_text
												return example

						_snake_case: List[str]	       =		train_dataset.map(lowercase__					,	remove_columns=[data_args.speech_file_column]    )
						_snake_case: Union[str, 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: Optional[Any]	       =		len(lowercase__    )
												_snake_case: int	       =		len(lowercase__    )
												_snake_case: Union[str, Any]	       =		train_dataset.filter(lowercase__					,	remove_columns=['duration_in_seconds']    )
												_snake_case: 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: List[str]	       =		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: Union[str, Any]	       =		processor(
												    audio=batch['speech']					,	text=batch[data_args.target_text_column]					,	sampling_rate=batch['sampling_rate'][0]    )
												batch.update(lowercase__    )
												return batch

						_snake_case: 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: Dict	       =		val_dataset.map(
						    lowercase__					,	batch_size=training_args.per_device_train_batch_size					,	batched=lowercase__					,	num_proc=data_args.preprocessing_num_workers					,	)

						_snake_case: Dict	       =		DataCollatorCTCWithPadding(processor=lowercase__					,	padding=lowercase__    )

						def compute_metrics(lowercase__    ):
												_snake_case: List[Any]	       =		pred.predictions
												_snake_case: Dict	       =		np.argmax(lowercase__					,	axis=-1    )

												_snake_case: Optional[Any]	       =		processor.tokenizer.pad_token_id

												_snake_case: Tuple	       =		processor.batch_decode(lowercase__    )
												# we do not want to group tokens when computing the metrics
												_snake_case: Union[str, Any]	       =		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: Any	       =		wer_metric.compute(predictions=lowercase__					,	references=lowercase__    )

												return {"wer": wer}

						if model_args.freeze_feature_extractor:
												model.freeze_feature_extractor()

						_snake_case: Union[str, Any]	       =		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 tempfile
import unittest

import numpy as np
import torch

from diffusers import DiffusionPipeline
from diffusers.models.attention_processor import Attention, AttnAddedKVProcessor







class       lowerCamelCase       (    unittest.TestCase	):


					def  SCREAMING_SNAKE_CASE_		(       self						:	List[Any]							,  __snake_case						:	bool = False							):





											'''simple docstring'''





											_snake_case: Any	       =		10

											if only_cross_attention:
																	_snake_case: Optional[int]	       =		12
											else:
																	# when only cross attention is not set, the cross attention dim must be the same as the query dim
																	_snake_case: Optional[int]	       =		query_dim

											return {
											    "query_dim": query_dim,
											    "cross_attention_dim": cross_attention_dim,
											    "heads": 2,
											    "dim_head": 4,
											    "added_kv_proj_dim": 6,
											    "norm_num_groups": 1,
											    "only_cross_attention": only_cross_attention,
											    "processor": AttnAddedKVProcessor(),
											}


					def  SCREAMING_SNAKE_CASE_		(       self						:	List[Any]							,  __snake_case						:	List[Any]							,  __snake_case						:	Tuple							):





											'''simple docstring'''





											_snake_case: Optional[int]	       =		2

											_snake_case: Union[str, Any]	       =		torch.rand(__snake_case							,  __snake_case							,  3							,  2							)
											_snake_case: Optional[int]	       =		torch.rand(__snake_case							,  4							,  __snake_case							)
											_snake_case: int	       =		None

											return {
											    "hidden_states": hidden_states,
											    "encoder_hidden_states": encoder_hidden_states,
											    "attention_mask": attention_mask,
											}




					def  SCREAMING_SNAKE_CASE_		(       self						:	List[Any]							):





											'''simple docstring'''





											torch.manual_seed(0							)

											_snake_case: int	       =		self.get_constructor_arguments(only_cross_attention=__snake_case							)
											_snake_case: Union[str, Any]	       =		Attention(**__snake_case							)

											self.assertTrue(attn.to_k is not None							)
											self.assertTrue(attn.to_v is not None							)

											_snake_case: Optional[int]	       =		self.get_forward_arguments(
											    query_dim=constructor_args['query_dim']							,  added_kv_proj_dim=constructor_args['added_kv_proj_dim']							)

											_snake_case: str	       =		attn(**__snake_case							)

											# only self attention

											torch.manual_seed(0							)

											_snake_case: str	       =		self.get_constructor_arguments(only_cross_attention=__snake_case							)
											_snake_case: Optional[Any]	       =		Attention(**__snake_case							)

											self.assertTrue(attn.to_k is None							)
											self.assertTrue(attn.to_v is None							)

											_snake_case: Dict	       =		self.get_forward_arguments(
											    query_dim=constructor_args['query_dim']							,  added_kv_proj_dim=constructor_args['added_kv_proj_dim']							)

											_snake_case: str	       =		attn(**__snake_case							)

											self.assertTrue((only_cross_attn_out != self_and_cross_attn_out).all()							)







class       lowerCamelCase       (    unittest.TestCase	):


					def  SCREAMING_SNAKE_CASE_		(       self						:	Tuple							):





											'''simple docstring'''





											_snake_case: str	       =		DiffusionPipeline.from_pretrained('hf-internal-testing/tiny-stable-diffusion-pipe'							,  safety_checker=__snake_case							)

											_snake_case: int	       =		pipe(
											    'foo'							,  num_inference_steps=2							,  generator=torch.Generator('cpu'							).manual_seed(0							)							,  output_type='np'							,  ).images

											# the initial conversion succeeds
											_snake_case: Dict	       =		DiffusionPipeline.from_pretrained(
											    'hf-internal-testing/tiny-stable-diffusion-pipe'							,  device_map='sequential'							,  safety_checker=__snake_case							)

											_snake_case: Any	       =		pipe(
											    'foo'							,  num_inference_steps=2							,  generator=torch.Generator('cpu'							).manual_seed(0							)							,  output_type='np'							,  ).images

											with tempfile.TemporaryDirectory() as tmpdir:
																	# save the converted model
																	pipe.save_pretrained(__snake_case							)

																	# can also load the converted weights
																	_snake_case: Union[str, Any]	       =		DiffusionPipeline.from_pretrained(__snake_case							,  device_map='sequential'							,  safety_checker=__snake_case							)

											_snake_case: Union[str, Any]	       =		pipe(
											    'foo'							,  num_inference_steps=2							,  generator=torch.Generator('cpu'							).manual_seed(0							)							,  output_type='np'							,  ).images

											self.assertTrue(np.allclose(__snake_case							,  __snake_case							,  atol=1e-5							)							)
											self.assertTrue(np.allclose(__snake_case							,  __snake_case							,  atol=1e-5							)							)





