




import inspect
import unittest

from transformers import EfficientNetConfig
from transformers.testing_utils import is_pipeline_test, require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
		import torch

		from transformers import EfficientNetForImageClassification, EfficientNetModel
		from transformers.models.efficientnet.modeling_efficientnet import EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import AutoImageProcessor
class 		UpperCAmelCase       :







						'''simple docstring'''





						def __init__(						self							:					Optional[int]	,     __lowercase							:					Optional[int]	,     __lowercase							:					List[str]=13	,     __lowercase							:					List[str]=32	,     __lowercase							:					Optional[int]=3	,     __lowercase							:					Optional[int]=[3, 3, 5]	,     __lowercase							:					Optional[int]=[32, 16, 24]	,     __lowercase							:					str=[16, 24, 40]	,     __lowercase							:					List[Any]=[1, 1, 2]	,     __lowercase							:					List[str]=[1, 1, 2]	,     __lowercase							:					int=[1, 6, 6]	,     __lowercase							:					List[Any]=True	,     __lowercase							:					Any=True	,     __lowercase							:					List[Any]=37	,     __lowercase							:					Optional[Any]="gelu"	,     __lowercase							:					Optional[int]=10	,     ):






							"""simple docstring"""






							snake_case_		   =					parent
							snake_case_		   =					batch_size
							snake_case_		   =					image_size
							snake_case_		   =					num_channels
							snake_case_		   =					kernel_sizes
							snake_case_		   =					in_channels
							snake_case_		   =					out_channels
							snake_case_		   =					strides
							snake_case_		   =					num_block_repeats
							snake_case_		   =					expand_ratios
							snake_case_		   =					is_training
							snake_case_		   =					hidden_act
							snake_case_		   =					num_labels
							snake_case_		   =					use_labels






						def 	snake_case__						(						self							:					Any						):






							"""simple docstring"""






							snake_case_		   =					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

							snake_case_		   =					None
							if self.use_labels:
								snake_case_		   =					ids_tensor([self.batch_size]	,     self.num_labels						)

							snake_case_		   =					self.get_config()
							return config, pixel_values, labels






						def 	snake_case__						(						self							:					Optional[Any]						):






							"""simple docstring"""






							return EfficientNetConfig(
							    num_channels=self.num_channels	,     kernel_sizes=self.kernel_sizes	,     in_channels=self.in_channels	,     out_channels=self.out_channels	,     strides=self.strides	,     num_block_repeats=self.num_block_repeats	,     expand_ratios=self.expand_ratios	,     hidden_act=self.hidden_act	,     num_labels=self.num_labels	,     )






						def 	snake_case__						(						self							:					Dict	,     __lowercase							:					Union[str, Any]	,     __lowercase							:					List[str]	,     __lowercase							:					List[str]						):






							"""simple docstring"""






							snake_case_		   =					EfficientNetModel(config=__lowercase						)
							model.to(__lowercase						)
							model.eval()
							snake_case_		   =					model(__lowercase						)
							# expected last hidden states: B, C, H // 4, W // 4
							self.parent.assertEqual(
							    result.last_hidden_state.shape	,     (self.batch_size, config.hidden_dim, self.image_size // 4, self.image_size // 4)	,     )






						def 	snake_case__						(						self							:					Optional[int]	,     __lowercase							:					Dict	,     __lowercase							:					Optional[Any]	,     __lowercase							:					str						):






							"""simple docstring"""






							snake_case_		   =					EfficientNetForImageClassification(__lowercase						)
							model.to(__lowercase						)
							model.eval()
							snake_case_		   =					model(__lowercase	,     labels=__lowercase						)
							self.parent.assertEqual(result.logits.shape	,     (self.batch_size, self.num_labels)						)






						def 	snake_case__						(						self							:					str						):






							"""simple docstring"""






							snake_case_		   =					self.prepare_config_and_inputs()
							snake_case_   ,				snake_case_   ,				snake_case_		   =					config_and_inputs
							snake_case_		   =					{"pixel_values": pixel_values}
							return config, inputs_dict







@require_torch
class 		UpperCAmelCase       (    UpperCAmelCase__	,       UpperCAmelCase__	,       unittest.TestCase      ):







						'''simple docstring'''





						lowerCAmelCase_							=       (EfficientNetModel, EfficientNetForImageClassification) if is_torch_available() else ()
						lowerCAmelCase_							=       (
						    {'''feature-extraction''': EfficientNetModel, '''image-classification''': EfficientNetForImageClassification}
						    if is_torch_available()
						    else {}
						)

						lowerCAmelCase_							=       False
						lowerCAmelCase_							=       False
						lowerCAmelCase_							=       False
						lowerCAmelCase_							=       False
						lowerCAmelCase_							=       False






						def 	snake_case__						(						self							:					str						):






							"""simple docstring"""






							snake_case_		   =					EfficientNetModelTester(self						)
							snake_case_		   =					ConfigTester(
							    self	,     config_class=__lowercase	,     has_text_modality=__lowercase	,     hidden_size=37						)






						def 	snake_case__						(						self							:					int						):






							"""simple docstring"""






							self.create_and_test_config_common_properties()
							self.config_tester.create_and_test_config_to_json_string()
							self.config_tester.create_and_test_config_to_json_file()
							self.config_tester.create_and_test_config_from_and_save_pretrained()
							self.config_tester.create_and_test_config_with_num_labels()
							self.config_tester.check_config_can_be_init_without_params()
							self.config_tester.check_config_arguments_init()






						def 	snake_case__						(						self							:					List[Any]						):






							"""simple docstring"""






							return






						@unittest.skip(reason="EfficientNet does not use inputs_embeds"						)
						def 	snake_case__						(						self							:					Dict						):






							"""simple docstring"""






							pass






						@unittest.skip(reason="EfficientNet does not support input and output embeddings"						)
						def 	snake_case__						(						self							:					str						):






							"""simple docstring"""






							pass






						@unittest.skip(reason="EfficientNet does not use feedforward chunking"						)
						def 	snake_case__						(						self							:					Dict						):






							"""simple docstring"""






							pass






						def 	snake_case__						(						self							:					str						):






							"""simple docstring"""






							snake_case_   ,				snake_case_		   =					self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
								snake_case_		   =					model_class(__lowercase						)
								snake_case_		   =					inspect.signature(model.forward						)
								# signature.parameters is an OrderedDict => so arg_names order is deterministic
								snake_case_		   =					[*signature.parameters.keys()]

								snake_case_		   =					["pixel_values"]
								self.assertListEqual(arg_names[:1]	,     __lowercase						)






						def 	snake_case__						(						self							:					Optional[int]						):






							"""simple docstring"""






							snake_case_		   =					self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*__lowercase						)






						def 	snake_case__						(						self							:					str						):






							"""simple docstring"""






							def check_hidden_states_output(__lowercase							:					Tuple	,     __lowercase							:					Any	,     __lowercase							:					Optional[int]						):
								snake_case_		   =					model_class(__lowercase						)
								model.to(__lowercase						)
								model.eval()

								with torch.no_grad():
									snake_case_		   =					model(**self._prepare_for_class(__lowercase	,     __lowercase						)						)

								snake_case_		   =					outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
								snake_case_		   =					sum(config.num_block_repeats						) * 4
								self.assertEqual(len(__lowercase						)	,     __lowercase						)

								# EfficientNet's feature maps are of shape (batch_size, num_channels, height, width)
								self.assertListEqual(
								    list(hidden_states[0].shape[-2:]						)	,     [self.model_tester.image_size // 2, self.model_tester.image_size // 2]	,     )

							snake_case_   ,				snake_case_		   =					self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
								snake_case_		   =					True
								check_hidden_states_output(__lowercase	,     __lowercase	,     __lowercase						)

								# check that output_hidden_states also work using config
								del inputs_dict["output_hidden_states"]
								snake_case_		   =					True

								check_hidden_states_output(__lowercase	,     __lowercase	,     __lowercase						)






						def 	snake_case__						(						self							:					Optional[int]						):






							"""simple docstring"""






							snake_case_		   =					self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*__lowercase						)






						@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."						)
						def 	snake_case__						(						self							:					Dict						):






							"""simple docstring"""






							pass






						@slow
						def 	snake_case__						(						self							:					int						):






							"""simple docstring"""






							for model_name in EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
								snake_case_		   =					EfficientNetModel.from_pretrained(__lowercase						)
								self.assertIsNotNone(__lowercase						)






						@is_pipeline_test
						@require_vision
						@slow
						def 	snake_case__						(						self							:					Union[str, Any]						):






							"""simple docstring"""






							super().test_pipeline_image_classification()







def 						lowerCamelCase__   (		):







	'''simple docstring'''





	snake_case_		   =					Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"							)
	return image






@require_torch
@require_vision
class 		UpperCAmelCase       (    unittest.TestCase      ):







						'''simple docstring'''





						@cached_property
						def 	snake_case__						(						self							:					Union[str, Any]						):






							"""simple docstring"""






							return AutoImageProcessor.from_pretrained("google/efficientnet-b7"						) if is_vision_available() else None






						@slow
						def 	snake_case__						(						self							:					Tuple						):






							"""simple docstring"""






							snake_case_		   =					EfficientNetForImageClassification.from_pretrained("google/efficientnet-b7"						).to(__lowercase						)

							snake_case_		   =					self.default_image_processor
							snake_case_		   =					prepare_img()
							snake_case_		   =					image_processor(images=__lowercase	,     return_tensors="pt"						).to(__lowercase						)

							# forward pass
							with torch.no_grad():
								snake_case_		   =					model(**__lowercase						)

							# verify the logits
							snake_case_		   =					torch.Size((1, 10_00)						)
							self.assertEqual(outputs.logits.shape	,     __lowercase						)

							snake_case_		   =					torch.tensor([0.0001, 0.0002, 0.0002]						).to(__lowercase						)
							self.assertTrue(torch.allclose(outputs.logits[0, :3]	,     __lowercase	,     atol=1E-4						)						)






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


lowercase__    :					Tuple					=						logging.getLogger(__name__)
@dataclass
class 		UpperCAmelCase       :







						'''simple docstring'''





						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 						lowerCamelCase__   (		_A					,     _A							):







	'''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_		   =					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(_A							)
@dataclass
class 		UpperCAmelCase       :







						'''simple docstring'''





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







						'''simple docstring'''





						lowerCAmelCase_							=       False
						lowerCAmelCase_							=       None
						lowerCAmelCase_							=       "|"
						lowerCAmelCase_							=       field(default_factory=UpperCAmelCase__      )
						lowerCAmelCase_							=       field(default_factory=UpperCAmelCase__      )
						lowerCAmelCase_							=       None






						@classmethod
						def 	snake_case__						(						cls							:					Optional[int]	,     __lowercase							:					str						):






							"""simple docstring"""






							if name == "librispeech":
								return cls()
							if name == "timit":
								return cls(
								    do_lower_case=__lowercase	,     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(__lowercase						).parent.joinpath("vocab/buckwalter.json"						)	,     word_delimiter_token="/"	,     translation_table=str.maketrans(__lowercase						)	,     words_to_remove={"sil"}	,     untransliterator=arabic.buckwalter.untransliterate	,     )
							raise ValueError(f"Unsupported orthography: '{name}'."						)






						def 	snake_case__						(						self							:					str	,     __lowercase							:					str						):






							"""simple docstring"""






							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							:					Dict	,     __lowercase							:					ModelArguments						):






							"""simple docstring"""






							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(__lowercase	,     __lowercase						)







@dataclass
class 		UpperCAmelCase       :







						'''simple docstring'''





						lowerCAmelCase_							=       42
						lowerCAmelCase_							=       True
						lowerCAmelCase_							=       None
						lowerCAmelCase_							=       None
						lowerCAmelCase_							=       None
						lowerCAmelCase_							=       None






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






							"""simple docstring"""






							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(
							    __lowercase	,     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=__lowercase	,     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_00						)

							snake_case_		   =					labels

							return batch







class 		UpperCAmelCase       (    UpperCAmelCase__      ):







						'''simple docstring'''





						def 	snake_case__						(						self							:					Dict	,     __lowercase							:					nn.Module	,     __lowercase							:					Dict[str, Union[torch.Tensor, Any]]						):






							"""simple docstring"""






							model.train()
							snake_case_		   =					self._prepare_inputs(__lowercase						)

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

							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(__lowercase						).backward()
							elif self.use_apex:
								with amp.scale_loss(__lowercase	,     self.optimizer						) as scaled_loss:
									scaled_loss.backward()
							elif self.deepspeed:
								self.deepspeed.backward(__lowercase						)
							else:
								loss.backward()

							return loss.detach()







def 						lowerCamelCase__   (		):







	'''simple docstring'''





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

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

	snake_case_		   =					Orthography.from_name(data_args.orthography.lower()							)
	snake_case_		   =					orthography.create_processor(_A							)
	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(_A							) == 1							)
	snake_case_		   =					re.compile(  # remove characters not in vocabulary
	    Rf"[^\s{re.escape(_A							)}]"					,     flags=re.IGNORECASE if processor.tokenizer.do_lower_case else 0					,     )
	snake_case_		   =					[]

	def prepare_example(_A							):  # TODO(elgeish) make use of multiprocessing?
		snake_case_   ,				snake_case_		   =					librosa.load(example[data_args.speech_file_column]					,     sr=_A							)
		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(""					,     _A							)
		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(_A					,     remove_columns=[data_args.speech_file_column]							)
	snake_case_		   =					val_dataset.map(_A					,     remove_columns=[data_args.speech_file_column]							)

	if data_args.max_duration_in_seconds is not None:

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

		snake_case_		   =					len(_A							)
		snake_case_		   =					len(_A							)
		snake_case_		   =					train_dataset.filter(_A					,     remove_columns=["duration_in_seconds"]							)
		snake_case_		   =					val_dataset.filter(_A					,     remove_columns=["duration_in_seconds"]							)
		if len(_A							) > old_train_size:
			logger.warning(
			    f"Filtered out {len(_A							) - old_train_size} train example(s) longer than"
			    f" {data_args.max_duration_in_seconds} second(s)."							)
		if len(_A							) > old_val_size:
			logger.warning(
			    f"Filtered out {len(_A							) - old_val_size} validation example(s) longer than"
			    f" {data_args.max_duration_in_seconds} second(s)."							)
	logger.info(f"Split sizes: {len(_A							)} train and {len(_A							)} validation."							)

	logger.warning(f"Updated {len(_A							)} 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(_A							):
		# 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(_A							)
		return batch

	snake_case_		   =					train_dataset.map(
	    _A					,     batch_size=training_args.per_device_train_batch_size					,     batched=_A					,     num_proc=data_args.preprocessing_num_workers					,     )
	snake_case_		   =					val_dataset.map(
	    _A					,     batch_size=training_args.per_device_train_batch_size					,     batched=_A					,     num_proc=data_args.preprocessing_num_workers					,     )

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

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

		snake_case_		   =					processor.tokenizer.pad_token_id

		snake_case_		   =					processor.batch_decode(_A							)
		# we do not want to group tokens when computing the metrics
		snake_case_		   =					processor.batch_decode(pred.label_ids					,     group_tokens=_A							)
		if logger.isEnabledFor(logging.DEBUG							):
			for reference, predicted in zip(_A					,     _A							):
				logger.debug(f"reference: \"{reference}\""							)
				logger.debug(f"predicted: \"{predicted}\""							)
				if orthography.untransliterator is not None:
					logger.debug(f"reference (untransliterated): \"{orthography.untransliterator(_A							)}\""							)
					logger.debug(f"predicted (untransliterated): \"{orthography.untransliterator(_A							)}\""							)

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

		return {"wer": wer}

	if model_args.freeze_feature_extractor:
		model.freeze_feature_extractor()

	snake_case_		   =					CTCTrainer(
	    model=_A					,     data_collator=_A					,     args=_A					,     compute_metrics=_A					,     train_dataset=_A					,     eval_dataset=_A					,     tokenizer=processor.feature_extractor					,     )

	trainer.train()


if __name__ == "__main__":
		main()
