

from typing import SupportsIndex

import numpy as np
from scipy.ndimage import convolve


def 						__SCREAMING_SNAKE_CASE      (SCREAMING_SNAKE_CASE__						,	SCREAMING_SNAKE_CASE__						,	SCREAMING_SNAKE_CASE__ )     ->   np.ndarray:
						snake_case_     =			np.stack((horizontal_flow, vertical_flow)						,	2 )

						# Create a grid of all pixel coordinates and subtract the flow to get the
						# target pixels coordinates
						snake_case_     =			np.stack(
						    np.meshgrid(np.arange(0						,	image.shape[1] )						,	np.arange(0						,	image.shape[0] ) )						,	2 )
						snake_case_     =			np.round(grid - flow ).astype(np.intaa )

						# Find the locations outside of the original image
						snake_case_     =			(grid < 0) | (grid >= np.array([image.shape[1], image.shape[0]] ))
						snake_case_     =			0

						snake_case_     =			image[grid[:, :, 1], grid[:, :, 0]]

						# Set pixels at invalid locations to 0
						snake_case_     =			0

						return warped


def 						__SCREAMING_SNAKE_CASE      (SCREAMING_SNAKE_CASE__						,	SCREAMING_SNAKE_CASE__						,	SCREAMING_SNAKE_CASE__						,	SCREAMING_SNAKE_CASE__ = None						,	)     ->   tuple[np.ndarray, np.ndarray]:
						if alpha is None:
												snake_case_     =			0.1

						# Initialize flow
						snake_case_     =			np.zeros_like(a_ )
						snake_case_     =			np.zeros_like(a_ )

						# Prepare kernels for the calculation of the derivatives and the average velocity
						snake_case_     =			np.array([[-1, 1], [-1, 1]] ) * 0.25
						snake_case_     =			np.array([[-1, -1], [1, 1]] ) * 0.25
						snake_case_     =			np.array([[1, 1], [1, 1]] ) * 0.25
						snake_case_     =			np.array(
						    [[1 / 12, 1 / 6, 1 / 12], [1 / 6, 0, 1 / 6], [1 / 12, 1 / 6, 1 / 12]] )

						# Iteratively refine the flow
						for _ in range(a_ ):
												snake_case_     =			warp(a_						,	a_						,	a_ )
												snake_case_     =			convolve(a_						,	a_ ) + convolve(a_						,	a_ )
												snake_case_     =			convolve(a_						,	a_ ) + convolve(a_						,	a_ )
												snake_case_     =			convolve(a_						,	a_ ) + convolve(a_						,	-kernel_t )

												snake_case_     =			convolve(a_						,	a_ )
												snake_case_     =			convolve(a_						,	a_ )

												# This updates the flow as proposed in the paper (Step 12)
												snake_case_     =			(
												    derivative_x * avg_horizontal_velocity
												    + derivative_y * avg_vertical_velocity
												    + derivative_t
												)
												snake_case_     =			update / (alpha**2 + derivative_x**2 + derivative_y**2)

												snake_case_     =			avg_horizontal_velocity - derivative_x * update
												snake_case_     =			avg_vertical_velocity - derivative_y * update

						return horizontal_flow, vertical_flow


if __name__ == "__main__":
					import doctest

					doctest.testmod()


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 			snake_case_     :







			'''simple docstring'''

			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=__A			, metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}			, )
			SCREAMING_SNAKE_CASE  :     Optional[bool]		    =       field(
			    default=__A			, metadata={"help": "Whether to freeze the feature extractor layers of the model."}      )
			SCREAMING_SNAKE_CASE  :     Optional[bool]		    =       field(
			    default=__A			, metadata={"help": "Whether to log verbose messages or not."}			, )






def 						__SCREAMING_SNAKE_CASE      (SCREAMING_SNAKE_CASE__						,	SCREAMING_SNAKE_CASE__ ):
						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_     =			logging.WARNING
						if model_args.verbose_logging:
												snake_case_     =			logging.DEBUG
						elif trainer_utils.is_main_process(training_args.local_rank ):
												snake_case_     =			logging.INFO
						logger.setLevel(SCREAMING_SNAKE_CASE__ )





@dataclass
class 			snake_case_     :







			'''simple docstring'''

			SCREAMING_SNAKE_CASE  :     str		    =       field(
			    default=__A			, metadata={"help": "The name of the dataset to use (via the datasets library)."}      )
			SCREAMING_SNAKE_CASE  :     Optional[str]		    =       field(
			    default=__A			, 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=__A			, metadata={"help": "Resample loaded audio to target feature extractor's sampling rate or not."}			, )
			SCREAMING_SNAKE_CASE  :     Optional[float]		    =       field(
			    default=__A			, 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=__A			, metadata={"help": "Overwrite the cached preprocessed datasets or not."}      )
			SCREAMING_SNAKE_CASE  :     Optional[int]		    =       field(
			    default=__A			, metadata={"help": "The number of processes to use for the preprocessing."}			, )






@dataclass
class 			snake_case_     :







			'''simple docstring'''

			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=__A      )
			SCREAMING_SNAKE_CASE  :     Optional[Set[str]]		    =       field(default_factory=__A      )
			SCREAMING_SNAKE_CASE  :     Optional[Callable[[str], str]]		    =       None







			@classmethod
			def        snake_case__(  cls				:       List[Any]							,     _UpperCamelCase				:       str							)   ->Any:
									if name == "librispeech":
															return cls()
									if name == "timit":
															return cls(
															    do_lower_case=_UpperCamelCase							,     translation_table=str.maketrans({'''-''': ''' '''}							)							,     )
									if name == "buckwalter":
															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        snake_case__(  self				:       List[Any]							,     _UpperCamelCase				:       str							)   ->str:
									# TODO(elgeish) return a pipeline (e.g., from jiwer) instead? Or rely on branch predictor as is
									if len(self.translation_table							) > 0:
															snake_case_     =			text.translate(self.translation_table							)
									if len(self.words_to_remove							) == 0:
															snake_case_     =			''' '''.join(text.split()							)  # clean up whitespaces
									else:
															snake_case_     =			''' '''.join(w for w in text.split() if w not in self.words_to_remove							)  # and clean up whilespaces
									return text







			def        snake_case__(  self				:       Tuple							,     _UpperCamelCase				:       ModelArguments							)   ->WavaVecaProcessor:
									snake_case_     =			WavaVecaFeatureExtractor.from_pretrained(
									    model_args.model_name_or_path							,     cache_dir=model_args.cache_dir							)
									if self.vocab_file:
															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:
															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 			snake_case_     :







			'''simple docstring'''

			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				:       Optional[Any]							,     _UpperCamelCase				:       List[Dict[str, Union[List[int], torch.Tensor]]]							)   ->Dict[str, torch.Tensor]:
									# split inputs and labels since they have to be of different lenghts and need
									# different padding methods
									snake_case_     =			[{'''input_values''': feature['''input_values''']} for feature in features]
									snake_case_     =			[{'''input_ids''': feature['''labels''']} for feature in features]

									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'''							,     )
									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
									snake_case_     =			labels_batch['''input_ids'''].masked_fill(labels_batch.attention_mask.ne(1							)							,     -1_0_0							)

									snake_case_     =			labels

									return batch






class 			snake_case_     (	__A      ):







			'''simple docstring'''

			def        snake_case__(  self				:       Tuple							,     _UpperCamelCase				:       nn.Module							,     _UpperCamelCase				:       Dict[str, Union[torch.Tensor, Any]]							)   ->torch.Tensor:
									model.train()
									snake_case_     =			self._prepare_inputs(_UpperCamelCase							)

									if self.use_amp:
															with autocast():
																					snake_case_     =			self.compute_loss(_UpperCamelCase							,     _UpperCamelCase							)
									else:
															snake_case_     =			self.compute_loss(_UpperCamelCase							,     _UpperCamelCase							)

									if self.args.n_gpu > 1:
															if model.module.config.ctc_loss_reduction == "mean":
																					snake_case_     =			loss.mean()
															elif model.module.config.ctc_loss_reduction == "sum":
																					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:
															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 						__SCREAMING_SNAKE_CASE      ():
						# 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_     =			HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) )

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

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

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

						snake_case_     =			datasets.load_metric('''wer''' )
						snake_case_     =			processor.feature_extractor.sampling_rate if data_args.target_feature_extractor_sampling_rate else None
						snake_case_     =			''''''.join(t for t in processor.tokenizer.get_vocab().keys() if len(SCREAMING_SNAKE_CASE__ ) == 1 )
						snake_case_     =			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						,	)
						snake_case_     =			[]

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

						snake_case_     =			train_dataset.map(SCREAMING_SNAKE_CASE__						,	remove_columns=[data_args.speech_file_column] )
						snake_case_     =			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

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

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

						snake_case_     =			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						,	)
						snake_case_     =			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						,	)

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

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

												snake_case_     =			processor.tokenizer.pad_token_id

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

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

												return {"wer": wer}

						if model_args.freeze_feature_extractor:
												model.freeze_feature_extractor()

						snake_case_     =			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()