

import copy
import os
from typing import Dict, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...utils import add_start_docstrings, logging
from ..auto import AutoConfig


lowerCAmelCase_ 			=			logging.get_logger(__name__)


lowerCAmelCase_ 			=			{
    '''suno/bark-small''': '''https://huggingface.co/suno/bark-small/resolve/main/config.json''',
    '''suno/bark''': '''https://huggingface.co/suno/bark/resolve/main/config.json''',
}

lowerCAmelCase_ 			=			'''
    This is the configuration class to store the configuration of a [`{model}`]. It is used to instantiate the model
    according to the specified arguments, defining the model architecture. Instantiating a configuration with the
    defaults will yield a similar configuration to that of the Bark [suno/bark](https://huggingface.co/suno/bark)
    architecture.

    Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
    documentation from [`PretrainedConfig`] for more information.

    Args:
        block_size (`int`, *optional*, defaults to 1024):
            The maximum sequence length that this model might ever be used with. Typically set this to something large
            just in case (e.g., 512 or 1024 or 2048).
        input_vocab_size (`int`, *optional*, defaults to 10_048):
            Vocabulary size of a Bark sub-model. Defines the number of different tokens that can be represented by the
            `inputs_ids` passed when calling [`{model}`]. Defaults to 10_048 but should be carefully thought with
            regards to the chosen sub-model.
        output_vocab_size (`int`, *optional*, defaults to 10_048):
            Output vocabulary size of a Bark sub-model. Defines the number of different tokens that can be represented
            by the: `output_ids` when passing forward a [`{model}`]. Defaults to 10_048 but should be carefully thought
            with regards to the chosen sub-model.
        num_layers (`int`, *optional*, defaults to 12):
            Number of hidden layers in the given sub-model.
        num_heads (`int`, *optional*, defaults to 12):
            Number of attention heads for each attention layer in the Transformer architecture.
        hidden_size (`int`, *optional*, defaults to 768):
            Dimensionality of the "intermediate" (often named feed-forward) layer in the architecture.
        dropout (`float`, *optional*, defaults to 0.0):
            The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
        bias (`bool`, *optional*, defaults to `True`):
            Whether or not to use bias in the linear layers and layer norm layers.
        initializer_range (`float`, *optional*, defaults to 0.02):
            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
        use_cache (`bool`, *optional*, defaults to `True`):
            Whether or not the model should return the last key/values attentions (not used by all models).
'''





class 			snake_case_     (	__A      ):







			'''simple docstring'''

			SCREAMING_SNAKE_CASE  :     Any		    =       "bark_module"
			SCREAMING_SNAKE_CASE  :     Dict		    =       ["past_key_values"]

			SCREAMING_SNAKE_CASE  :     Dict		    =       {
			    "num_attention_heads": "num_heads",
			    "num_hidden_layers": "num_layers",
			    "vocab_size": "input_vocab_size",
			    "window_size": "block_size",
			}







			def __init__(  self				:       Tuple							,     _UpperCamelCase				:       Any=1_0_2_4							,     _UpperCamelCase				:       List[Any]=1_0_0_4_8							,     _UpperCamelCase				:       Optional[int]=1_0_0_4_8							,     _UpperCamelCase				:       Optional[int]=1_2							,     _UpperCamelCase				:       Optional[int]=1_2							,     _UpperCamelCase				:       str=7_6_8							,     _UpperCamelCase				:       Optional[int]=0.0							,     _UpperCamelCase				:       Union[str, Any]=True							,     _UpperCamelCase				:       Dict=0.02							,     _UpperCamelCase				:       int=True							,     **_UpperCamelCase				:       int							,     )   ->Optional[int]:
									snake_case_     =			block_size
									snake_case_     =			input_vocab_size
									snake_case_     =			output_vocab_size
									snake_case_     =			num_layers
									snake_case_     =			num_heads
									snake_case_     =			hidden_size
									snake_case_     =			dropout
									snake_case_     =			bias
									snake_case_     =			use_cache
									snake_case_     =			initializer_range

									super().__init__(**_UpperCamelCase							)







			@classmethod
			def        snake_case__(  cls				:       Union[str, Any]							,     _UpperCamelCase				:       Union[str, os.PathLike]							,     _UpperCamelCase				:       Optional[Union[str, os.PathLike]] = None							,     _UpperCamelCase				:       bool = False							,     _UpperCamelCase				:       bool = False							,     _UpperCamelCase				:       Optional[Union[str, bool]] = None							,     _UpperCamelCase				:       str = "main"							,     **_UpperCamelCase				:       Optional[int]							,     )   ->"PretrainedConfig":
									snake_case_     =			cache_dir
									snake_case_     =			force_download
									snake_case_     =			local_files_only
									snake_case_     =			revision

									cls._set_token_in_kwargs(_UpperCamelCase							,     _UpperCamelCase							)

									snake_case_,					snake_case_     =			cls.get_config_dict(_UpperCamelCase							,     **_UpperCamelCase							)

									# get the config dict if we are loading from Bark
									if config_dict.get('''model_type'''							) == "bark":
															snake_case_     =			config_dict[f'''{cls.model_type}_config''']

									if "model_type" in config_dict and hasattr(cls							,     '''model_type'''							) and config_dict["model_type"] != cls.model_type:
															logger.warning(
															    f'''You are using a model of type {config_dict['model_type']} to instantiate a model of type '''
															    f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.'''							)

									return cls.from_dict(_UpperCamelCase							,     **_UpperCamelCase							)






@add_start_docstrings(
    BARK_SUBMODELCONFIG_START_DOCSTRING.format(config="BarkSemanticConfig"			, model="BarkSemanticModel"      )			, "\n    Example:\n\n    ```python\n    >>> from transformers import BarkSemanticConfig, BarkSemanticModel\n\n    >>> # Initializing a Bark sub-module style configuration\n    >>> configuration = BarkSemanticConfig()\n\n    >>> # Initializing a model (with random weights) from the suno/bark style configuration\n    >>> model = BarkSemanticModel(configuration)\n\n    >>> # Accessing the model configuration\n    >>> configuration = model.config\n    ```"			, )
class 			snake_case_     (	__A      ):







			'''simple docstring'''

			SCREAMING_SNAKE_CASE  :     Union[str, Any]		    =       "semantic"






@add_start_docstrings(
    BARK_SUBMODELCONFIG_START_DOCSTRING.format(config="BarkCoarseConfig"			, model="BarkCoarseModel"      )			, "\n    Example:\n\n    ```python\n    >>> from transformers import BarkCoarseConfig, BarkCoarseModel\n\n    >>> # Initializing a Bark sub-module style configuration\n    >>> configuration = BarkCoarseConfig()\n\n    >>> # Initializing a model (with random weights) from the suno/bark style configuration\n    >>> model = BarkCoarseModel(configuration)\n\n    >>> # Accessing the model configuration\n    >>> configuration = model.config\n    ```"			, )
class 			snake_case_     (	__A      ):







			'''simple docstring'''

			SCREAMING_SNAKE_CASE  :     Any		    =       "coarse_acoustics"






@add_start_docstrings(
    BARK_SUBMODELCONFIG_START_DOCSTRING.format(config="BarkFineConfig"			, model="BarkFineModel"      )			, "\n        n_codes_total (`int`, *optional*, defaults to 8):\n            The total number of audio codebooks predicted. Used in the fine acoustics sub-model.\n        n_codes_given (`int`, *optional*, defaults to 1):\n            The number of audio codebooks predicted in the coarse acoustics sub-model. Used in the acoustics\n            sub-models.\n    Example:\n\n    ```python\n    >>> from transformers import BarkFineConfig, BarkFineModel\n\n    >>> # Initializing a Bark sub-module style configuration\n    >>> configuration = BarkFineConfig()\n\n    >>> # Initializing a model (with random weights) from the suno/bark style configuration\n    >>> model = BarkFineModel(configuration)\n\n    >>> # Accessing the model configuration\n    >>> configuration = model.config\n    ```"			, )
class 			snake_case_     (	__A      ):







			'''simple docstring'''

			SCREAMING_SNAKE_CASE  :     Tuple		    =       "fine_acoustics"







			def __init__(  self				:       Union[str, Any]							,     _UpperCamelCase				:       Optional[Any]=True							,     _UpperCamelCase				:       Dict=8							,     _UpperCamelCase				:       Optional[Any]=1							,     **_UpperCamelCase				:       Union[str, Any]							)   ->Tuple:
									snake_case_     =			n_codes_total
									snake_case_     =			n_codes_given

									super().__init__(tie_word_embeddings=_UpperCamelCase							,     **_UpperCamelCase							)






class 			snake_case_     (	__A      ):







			'''simple docstring'''

			SCREAMING_SNAKE_CASE  :     List[Any]		    =       "bark"
			SCREAMING_SNAKE_CASE  :     Optional[int]		    =       True







			def __init__(  self				:       int							,     _UpperCamelCase				:       Dict = None							,     _UpperCamelCase				:       Dict = None							,     _UpperCamelCase				:       Dict = None							,     _UpperCamelCase				:       Dict = None							,     _UpperCamelCase				:       Any=0.02							,     **_UpperCamelCase				:       Optional[int]							,     )   ->Tuple:
									if semantic_config is None:
															snake_case_     =			{}
															logger.info('''semantic_config is None. initializing the semantic model with default values.'''							)

									if coarse_acoustics_config is None:
															snake_case_     =			{}
															logger.info('''coarse_acoustics_config is None. initializing the coarse model with default values.'''							)

									if fine_acoustics_config is None:
															snake_case_     =			{}
															logger.info('''fine_acoustics_config is None. initializing the fine model with default values.'''							)

									if codec_config is None:
															snake_case_     =			{}
															logger.info('''codec_config is None. initializing the codec model with default values.'''							)

									snake_case_     =			BarkSemanticConfig(**_UpperCamelCase							)
									snake_case_     =			BarkCoarseConfig(**_UpperCamelCase							)
									snake_case_     =			BarkFineConfig(**_UpperCamelCase							)
									snake_case_     =			AutoConfig.for_model(**_UpperCamelCase							)

									snake_case_     =			initializer_range

									super().__init__(**_UpperCamelCase							)







			@classmethod
			def        snake_case__(  cls				:       Optional[int]							,     _UpperCamelCase				:       BarkSemanticConfig							,     _UpperCamelCase				:       BarkCoarseConfig							,     _UpperCamelCase				:       BarkFineConfig							,     _UpperCamelCase				:       AutoConfig							,     **_UpperCamelCase				:       List[str]							,     )   ->List[str]:
									return cls(
									    semantic_config=semantic_config.to_dict()							,     coarse_acoustics_config=coarse_acoustics_config.to_dict()							,     fine_acoustics_config=fine_acoustics_config.to_dict()							,     codec_config=codec_config.to_dict()							,     **_UpperCamelCase							,     )







			def        snake_case__(  self				:       Any							)   ->Union[str, Any]:
									snake_case_     =			copy.deepcopy(self.__dict__							)

									snake_case_     =			self.semantic_config.to_dict()
									snake_case_     =			self.coarse_acoustics_config.to_dict()
									snake_case_     =			self.fine_acoustics_config.to_dict()
									snake_case_     =			self.codec_config.to_dict()

									snake_case_     =			self.__class__.model_type
									return output


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