






import asyncio
import os
import re
import sys
import tempfile
import unittest
from contextlib import contextmanager
from copy import deepcopy
from distutils.util import strtobool
from enum import Enum
from importlib.util import find_spec
from pathlib import Path
from unittest.mock import patch

import pyarrow as pa
import pytest
import requests
from packaging import version

from datasets import config


if config.PY_VERSION < version.parse('''3.8'''):
	import importlib_metadata
else:
	import importlib.metadata as importlib_metadata

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  str	,			__magic_name__					:  Optional[int]=False					)		->			Tuple:






	"""simple docstring"""



	try:
		UpperCamelCase     :str          =	os.environ[key]
	except KeyError:
		# KEY isn't set, default to `default`.
		UpperCamelCase     :str          =	default
	else:
		# KEY is set, convert it to True or False.
		try:
			UpperCamelCase     :Union[str, Any]          =	strtobool(__magic_name__					)
		except ValueError:
			# More values are supported, but let's keep the message simple.
			raise ValueError(f"""If set, {key} must be yes or no."""					)
	return _value


UpperCAmelCase_ :						Any      =      parse_flag_from_env('''RUN_SLOW''', default=False)
UpperCAmelCase_ :						Optional[Any]      =      parse_flag_from_env('''RUN_REMOTE''', default=False)
UpperCAmelCase_ :						Dict      =      parse_flag_from_env('''RUN_LOCAL''', default=True)
UpperCAmelCase_ :						str      =      parse_flag_from_env('''RUN_PACKAGED''', default=True)

# Compression
UpperCAmelCase_ :						str      =      pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='''test requires lz4''')
UpperCAmelCase_ :						Optional[Any]      =      pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='''test requires py7zr''')
UpperCAmelCase_ :						str      =      pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='''test requires zstandard''')

# Audio
UpperCAmelCase_ :						str      =      pytest.mark.skipif(
    # On Windows and OS X, soundfile installs sndfile
    find_spec('''soundfile''') is None or version.parse(importlib_metadata.version('''soundfile''')) < version.parse('''0.12.0'''),
    reason='''test requires sndfile>=0.12.1: \'pip install \"soundfile>=0.12.1\"\'; ''',
)

# Beam
UpperCAmelCase_ :						Any      =      pytest.mark.skipif(
    not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse('''0.3.2'''),
    reason='''test requires apache-beam and a compatible dill version''',
)

# Dill-cloudpickle compatibility
UpperCAmelCase_ :						Optional[int]      =      pytest.mark.skipif(
    config.DILL_VERSION <= version.parse('''0.3.2'''),
    reason='''test requires dill>0.3.2 for cloudpickle compatibility''',
)

# Windows
UpperCAmelCase_ :						Optional[Any]      =      pytest.mark.skipif(
    sys.platform == '''win32''',
    reason='''test should not be run on Windows''',
)

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Dict					)		->			Any:






	"""simple docstring"""



	try:
		import faiss  # noqa
	except ImportError:
		UpperCamelCase     :List[str]          =	unittest.skip("""test requires faiss"""					)(__magic_name__					)
	return test_case

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Tuple					)		->			int:






	"""simple docstring"""



	try:
		import regex  # noqa
	except ImportError:
		UpperCamelCase     :Dict          =	unittest.skip("""test requires regex"""					)(__magic_name__					)
	return test_case

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Any					)		->			Dict:






	"""simple docstring"""



	try:
		import elasticsearch  # noqa
	except ImportError:
		UpperCamelCase     :int          =	unittest.skip("""test requires elasticsearch"""					)(__magic_name__					)
	return test_case

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  str					)		->			Dict:






	"""simple docstring"""



	try:
		import sqlalchemy  # noqa
	except ImportError:
		UpperCamelCase     :Tuple          =	unittest.skip("""test requires sqlalchemy"""					)(__magic_name__					)
	return test_case

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Any					)		->			List[Any]:






	"""simple docstring"""



	if not config.TORCH_AVAILABLE:
		UpperCamelCase     :int          =	unittest.skip("""test requires PyTorch"""					)(__magic_name__					)
	return test_case

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Optional[Any]					)		->			List[Any]:






	"""simple docstring"""



	if not config.TF_AVAILABLE:
		UpperCamelCase     :str          =	unittest.skip("""test requires TensorFlow"""					)(__magic_name__					)
	return test_case

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  List[Any]					)		->			Optional[Any]:






	"""simple docstring"""



	if not config.JAX_AVAILABLE:
		UpperCamelCase     :Optional[int]          =	unittest.skip("""test requires JAX"""					)(__magic_name__					)
	return test_case

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Optional[Any]					)		->			Union[str, Any]:






	"""simple docstring"""



	if not config.PIL_AVAILABLE:
		UpperCamelCase     :int          =	unittest.skip("""test requires Pillow"""					)(__magic_name__					)
	return test_case

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Optional[int]					)		->			Dict:






	"""simple docstring"""



	try:
		import transformers  # noqa F401
	except ImportError:
		return unittest.skip("""test requires transformers"""					)(__magic_name__					)
	else:
		return test_case

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  str					)		->			int:






	"""simple docstring"""



	try:
		import tiktoken  # noqa F401
	except ImportError:
		return unittest.skip("""test requires tiktoken"""					)(__magic_name__					)
	else:
		return test_case

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  List[Any]					)		->			List[str]:






	"""simple docstring"""



	try:
		import spacy  # noqa F401
	except ImportError:
		return unittest.skip("""test requires spacy"""					)(__magic_name__					)
	else:
		return test_case

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Optional[Any]					)		->			Tuple:






	"""simple docstring"""



	def _require_spacy_model(__magic_name__					:  List[str]					):
		try:
			import spacy  # noqa F401

			spacy.load(__magic_name__					)
		except ImportError:
			return unittest.skip("""test requires spacy"""					)(__magic_name__					)
		except OSError:
			return unittest.skip("""test requires spacy model '{}'""".format(__magic_name__					)					)(__magic_name__					)
		else:
			return test_case

	return _require_spacy_model

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Tuple					)		->			List[Any]:






	"""simple docstring"""



	try:
		import pyspark  # noqa F401
	except ImportError:
		return unittest.skip("""test requires pyspark"""					)(__magic_name__					)
	else:
		return test_case

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Tuple					)		->			Optional[int]:






	"""simple docstring"""



	try:
		import joblibspark  # noqa F401
	except ImportError:
		return unittest.skip("""test requires joblibspark"""					)(__magic_name__					)
	else:
		return test_case

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  str					)		->			List[str]:






	"""simple docstring"""



	if not _run_slow_tests or _run_slow_tests == 0:
		UpperCamelCase     :Optional[int]          =	unittest.skip("""test is slow"""					)(__magic_name__					)
	return test_case

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Any					)		->			Union[str, Any]:






	"""simple docstring"""



	if not _run_local_tests or _run_local_tests == 0:
		UpperCamelCase     :str          =	unittest.skip("""test is local"""					)(__magic_name__					)
	return test_case

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Any					)		->			int:






	"""simple docstring"""



	if not _run_packaged_tests or _run_packaged_tests == 0:
		UpperCamelCase     :Optional[int]          =	unittest.skip("""test is packaged"""					)(__magic_name__					)
	return test_case

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Optional[Any]					)		->			Union[str, Any]:






	"""simple docstring"""



	if not _run_remote_tests or _run_remote_tests == 0:
		UpperCamelCase     :Optional[int]          =	unittest.skip("""test requires remote"""					)(__magic_name__					)
	return test_case

def    SCREAMING_SNAKE_CASE_							(							*__magic_name__					:  int					)		->			List[str]:






	"""simple docstring"""



	def decorate(cls					:  int					):
		for name, fn in cls.__dict__.items():
			if callable(__magic_name__					) and name.startswith("""test"""					):
				for decorator in decorators:
					UpperCamelCase     :int          =	decorator(__magic_name__					)
				setattr(cls	,			__magic_name__	,			__magic_name__					)
		return cls

	return decorate

class     _SCREAMING_SNAKE_CASE       (			_a      ):
	pass

class     _SCREAMING_SNAKE_CASE       (			_a      ):
	snake_case__							:     Union[str, Any]     	=  0
	snake_case__							:     Union[str, Any]     	=  1
	snake_case__							:     List[str]     	=  2

@contextmanager
def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Dict=OfflineSimulationMode.CONNECTION_FAILS	,			__magic_name__					:  str=1E-16					)		->			Any:






	"""simple docstring"""



	UpperCamelCase     :Optional[int]          =	requests.Session().request

	def timeout_request(__magic_name__					:  str	,			__magic_name__					:  List[str]	,			__magic_name__					:  Optional[int]	,			**__magic_name__					:  Dict					):
		# Change the url to an invalid url so that the connection hangs
		UpperCamelCase     :Dict          =	"""https://10.255.255.1"""
		if kwargs.get("""timeout"""					) is None:
			raise RequestWouldHangIndefinitelyError(
			    f"""Tried a call to {url} in offline mode with no timeout set. Please set a timeout."""					)
		UpperCamelCase     :List[str]          =	timeout
		try:
			return online_request(__magic_name__	,			__magic_name__	,			**__magic_name__					)
		except Exception as e:
			# The following changes in the error are just here to make the offline timeout error prettier
			UpperCamelCase     :Any          =	url
			UpperCamelCase     :Any          =	e.args[0]
			UpperCamelCase     :Tuple          =	(max_retry_error.args[0].replace("""10.255.255.1"""	,			f"""OfflineMock[{url}]"""					),)
			UpperCamelCase     :List[str]          =	(max_retry_error,)
			raise

	def raise_connection_error(__magic_name__					:  Tuple	,			__magic_name__					:  int	,			**__magic_name__					:  str					):
		raise requests.ConnectionError("""Offline mode is enabled."""	,			request=__magic_name__					)

	if mode is OfflineSimulationMode.CONNECTION_FAILS:
		with patch("""requests.Session.send"""	,			__magic_name__					):
			yield
	elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT:
		# inspired from https://stackoverflow.com/a/904609
		with patch("""requests.Session.request"""	,			__magic_name__					):
			yield
	elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1:
		with patch("""datasets.config.HF_DATASETS_OFFLINE"""	,			__magic_name__					):
			yield
	else:
		raise ValueError("""Please use a value from the OfflineSimulationMode enum."""					)

@contextmanager
def    SCREAMING_SNAKE_CASE_							(							*__magic_name__					:  str	,			**__magic_name__					:  Dict					)		->			List[Any]:






	"""simple docstring"""



	UpperCamelCase     :Optional[int]          =	str(Path().resolve()					)
	with tempfile.TemporaryDirectory(*__magic_name__	,			**__magic_name__					) as tmp_dir:
		try:
			os.chdir(__magic_name__					)
			yield
		finally:
			os.chdir(__magic_name__					)

@contextmanager
def    SCREAMING_SNAKE_CASE_							(							)		->			Optional[int]:






	"""simple docstring"""



	import gc

	gc.collect()
	UpperCamelCase     :Tuple          =	pa.total_allocated_bytes()
	yield
	assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."

@contextmanager
def    SCREAMING_SNAKE_CASE_							(							)		->			Optional[Any]:






	"""simple docstring"""



	import gc

	gc.collect()
	UpperCamelCase     :Dict          =	pa.total_allocated_bytes()
	yield
	assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase."

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Dict	,			__magic_name__					:  Dict					)		->			Tuple:






	"""simple docstring"""



	return deepcopy(__magic_name__					).integers(0	,			100	,			10					).tolist() == deepcopy(__magic_name__					).integers(0	,			100	,			10					).tolist()

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  List[str]					)		->			Union[str, Any]:






	"""simple docstring"""



	import decorator
	from requests.exceptions import HTTPError

	def _wrapper(__magic_name__					:  Tuple	,			*__magic_name__					:  List[str]	,			**__magic_name__					:  List[Any]					):
		try:
			return func(*__magic_name__	,			**__magic_name__					)
		except HTTPError as err:
			if str(__magic_name__					).startswith("""500"""					) or str(__magic_name__					).startswith("""502"""					):
				pytest.xfail(str(__magic_name__					)					)
			raise err

	return decorator.decorator(_wrapper	,			__magic_name__					)

class     _SCREAMING_SNAKE_CASE       :





	def __init__(		self				:					Tuple ,  __lowerCamelCase				:					Dict ,  __lowerCamelCase				:					Union[str, Any] ,  __lowerCamelCase				:					Any	):
		UpperCamelCase     :int          =	returncode
		UpperCamelCase     :Tuple          =	stdout
		UpperCamelCase     :List[str]          =	stderr

async def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Dict	,			__magic_name__					:  List[str]					)		->			Union[str, Any]:






	"""simple docstring"""



	while True:
		UpperCamelCase     :List[str]          =	await stream.readline()
		if line:
			callback(__magic_name__					)
		else:
			break

async def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  Tuple	,			__magic_name__					:  List[str]=None	,			__magic_name__					:  Optional[int]=None	,			__magic_name__					:  int=None	,			__magic_name__					:  int=False	,			__magic_name__					:  str=False					)		->			_RunOutput:






	"""simple docstring"""



	if echo:
		print("""\nRunning: """	,			""" """.join(__magic_name__					)					)

	UpperCamelCase     :List[str]          =	await asyncio.create_subprocess_exec(
	    cmd[0]	,			*cmd[1:]	,			stdin=__magic_name__	,			stdout=asyncio.subprocess.PIPE	,			stderr=asyncio.subprocess.PIPE	,			env=__magic_name__	,			)

	# note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
	# https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
	#
	# If it starts hanging, will need to switch to the following code. The problem is that no data
	# will be seen until it's done and if it hangs for example there will be no debug info.
	# out, err = await p.communicate()
	# return _RunOutput(p.returncode, out, err)

	UpperCamelCase     :List[Any]          =	[]
	UpperCamelCase     :List[Any]          =	[]

	def tee(__magic_name__					:  List[str]	,			__magic_name__					:  List[Any]	,			__magic_name__					:  int	,			__magic_name__					:  Optional[Any]=""					):
		UpperCamelCase     :List[Any]          =	line.decode("""utf-8"""					).rstrip()
		sink.append(__magic_name__					)
		if not quiet:
			print(__magic_name__	,			__magic_name__	,			file=__magic_name__					)

    # XXX: the timeout doesn't seem to make any difference here
	await asyncio.wait(
	    [
	        _read_stream(p.stdout	,			lambda __magic_name__					: tee(__magic_name__	,			__magic_name__	,			sys.stdout	,			label="""stdout:"""					)					),
	        _read_stream(p.stderr	,			lambda __magic_name__					: tee(__magic_name__	,			__magic_name__	,			sys.stderr	,			label="""stderr:"""					)					),
	    ]	,			timeout=__magic_name__	,			)
	return _RunOutput(await p.wait()	,			__magic_name__	,			__magic_name__					)

def    SCREAMING_SNAKE_CASE_							(							__magic_name__					:  int	,			__magic_name__					:  List[Any]=None	,			__magic_name__					:  Optional[Any]=None	,			__magic_name__					:  List[str]=180	,			__magic_name__					:  Optional[Any]=False	,			__magic_name__					:  Any=True					)		->			_RunOutput:






	"""simple docstring"""



	UpperCamelCase     :str          =	asyncio.get_event_loop()
	UpperCamelCase     :Optional[int]          =	loop.run_until_complete(
	    _stream_subprocess(__magic_name__	,			env=__magic_name__	,			stdin=__magic_name__	,			timeout=__magic_name__	,			quiet=__magic_name__	,			echo=__magic_name__					)					)

	UpperCamelCase     :Tuple          =	""" """.join(__magic_name__					)
	if result.returncode > 0:
		UpperCamelCase     :int          =	"""\n""".join(result.stderr					)
		raise RuntimeError(
		    f"""'{cmd_str}' failed with returncode {result.returncode}\n\n"""
		    f"""The combined stderr from workers follows:\n{stderr}"""					)

	# check that the subprocess actually did run and produced some output, should the test rely on
	# the remote side to do the testing
	if not result.stdout and not result.stderr:
		raise RuntimeError(f"""'{cmd_str}' produced no output."""					)

	return result

def    SCREAMING_SNAKE_CASE_							(							)		->			Union[str, Any]:






	"""simple docstring"""



	UpperCamelCase     :int          =	os.environ.get("""PYTEST_XDIST_WORKER"""	,			"""gw0"""					)
	UpperCamelCase     :str          =	re.sub(R"""^gw"""	,			""""""	,			__magic_name__	,			0	,			re.M					)
	return int(__magic_name__					)

def    SCREAMING_SNAKE_CASE_							(							)		->			Any:






	"""simple docstring"""



	UpperCamelCase     :Union[str, Any]          =	2_9500
	UpperCamelCase     :Union[str, Any]          =	pytest_xdist_worker_id()
	return port + uniq_delta




import json
import logging
import os
import re
import sys
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Union

import datasets
import numpy as np
import torch
import torchaudio
from packaging import version
from torch import nn

import transformers
from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaForCTC,
    WavaVecaProcessor,
    is_apex_available,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint, is_main_process


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




def 	a_      (    SCREAMING_SNAKE_CASE__					:      Optional[Any]=None		,			SCREAMING_SNAKE_CASE__					:      List[Any]=None     ):
       '''simple docstring'''





       return field(default_factory=lambda: default		,			metadata=SCREAMING_SNAKE_CASE__     )




@dataclass
class A  :
      UpperCamelCase__							:  str      =field(
          metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'}     )
      UpperCamelCase__							:  Optional[str]      =field(
          default=UpperCamelCase_    ,							metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'}    ,							)
      UpperCamelCase__							:  Optional[bool]      =field(
          default=UpperCamelCase_    ,							metadata={'help': 'Whether to freeze the feature extractor layers of the model.'}     )
      UpperCamelCase__							:  Optional[float]      =field(
          default=0.1    ,							metadata={'help': 'The dropout ratio for the attention probabilities.'}     )
      UpperCamelCase__							:  Optional[float]      =field(
          default=0.1    ,							metadata={'help': 'The dropout ratio for activations inside the fully connected layer.'}     )
      UpperCamelCase__							:  Optional[float]      =field(
          default=0.1    ,							metadata={
              'help': 'The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.'
          }    ,							)
      UpperCamelCase__							:  Optional[float]      =field(
          default=0.1    ,							metadata={'help': 'The dropout probabilitiy for all 1D convolutional layers in feature extractor.'}    ,							)
      UpperCamelCase__							:  Optional[float]      =field(
          default=0.05    ,							metadata={
              'help': (
                  'Propability of each feature vector along the time axis to be chosen as the start of the vector'
                  'span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature'
                  'vectors will be masked along the time axis. This is only relevant if ``apply_spec_augment is True``.'
              )
          }    ,							)
      UpperCamelCase__							:  Optional[float]      =field(default=0.0    ,							metadata={'help': 'The LayerDrop probability.'}     )




@dataclass
class A  :
      UpperCamelCase__							:  Optional[str]      =field(
          default=UpperCamelCase_    ,							metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'}     )
      UpperCamelCase__							:  Optional[str]      =field(
          default='train+validation'    ,							metadata={
              'help': 'The name of the training data set split to use (via the datasets library). Defaults to \'train\''
          }    ,							)
      UpperCamelCase__							:  bool      =field(
          default=UpperCamelCase_    ,							metadata={'help': 'Overwrite the cached preprocessed datasets or not.'}     )
      UpperCamelCase__							:  Optional[int]      =field(
          default=UpperCamelCase_    ,							metadata={'help': 'The number of processes to use for the preprocessing.'}    ,							)
      UpperCamelCase__							:  Optional[int]      =field(
          default=UpperCamelCase_    ,							metadata={
              'help': (
                  'For debugging purposes or quicker training, truncate the number of training examples to this '
                  'value if set.'
              )
          }    ,							)
      UpperCamelCase__							:  Optional[int]      =field(
          default=UpperCamelCase_    ,							metadata={
              'help': (
                  'For debugging purposes or quicker training, truncate the number of validation examples to this '
                  'value if set.'
              )
          }    ,							)
      UpperCamelCase__							:  List[str]      =list_field(
          default=[',', '?', '.', '!', '-', ';', ':', '""', '%', '\'', '"', '�']    ,							metadata={'help': 'A list of characters to remove from the transcripts.'}    ,							)




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






      def __call__(					self						:     str			,   lowercase_						:     List[Dict[str, Union[List[int], torch.Tensor]]] )					->						Dict[str, torch.Tensor]:
             """simple docstring"""




             _lowerCamelCase       :		List[Any]		=[{'input_values': feature['input_values']} for feature in features]
             _lowerCamelCase       :		str		=[{'input_ids': feature['labels']} for feature in features]

             _lowerCamelCase       :		Union[str, Any]		=self.processor.pad(
                 lowercase_			,   padding=self.padding			,   max_length=self.max_length			,   pad_to_multiple_of=self.pad_to_multiple_of			,   return_tensors='pt'			,   )
             _lowerCamelCase       :		Any		=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
             _lowerCamelCase       :		str		=labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1 )			,   -100 )

             _lowerCamelCase       :		List[Any]		=labels

             return batch




class A  (   UpperCamelCase_     ):






      def        lowerCamelCase       (					self						:     Optional[Any]			,   lowercase_						:     nn.Module			,   lowercase_						:     Dict[str, Union[torch.Tensor, Any]] )					->						torch.Tensor:
             """simple docstring"""




             model.train()
             _lowerCamelCase       :		List[Any]		=self._prepare_inputs(lowercase_ )

             if self.use_amp:
                    with autocast():
                           _lowerCamelCase       :		List[Any]		=self.compute_loss(lowercase_			,   lowercase_ )
             else:
                    _lowerCamelCase       :		Optional[int]		=self.compute_loss(lowercase_			,   lowercase_ )

             if self.args.n_gpu > 1:
                    if model.module.config.ctc_loss_reduction == "mean":
                           _lowerCamelCase       :		Optional[Any]		=loss.mean()
                    elif model.module.config.ctc_loss_reduction == "sum":
                           _lowerCamelCase       :		int		=loss.sum() / (inputs['labels'] >= 0).sum()
                    else:
                           raise ValueError(F'''{model.config.ctc_loss_reduction} is not valid. Choose one of [\'mean\', \'sum\']''' )

             if self.args.gradient_accumulation_steps > 1:
                    _lowerCamelCase       :		Dict		=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 	a_      (    ):
       '''simple docstring'''





       _lowerCamelCase       :		Union[str, Any]		=HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)     )
       if len(sys.argv     ) == 2 and sys.argv[1].endswith('.json'     ):
              # If we pass only one argument to the script and it's the path to a json file,
              # let's parse it to get our arguments.
              _lowerCamelCase	,     _lowerCamelCase	,     _lowerCamelCase       :		Tuple		=parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]     )     )
       else:
              _lowerCamelCase	,     _lowerCamelCase	,     _lowerCamelCase       :		Any		=parser.parse_args_into_dataclasses()

       # Detecting last checkpoint.
       _lowerCamelCase       :		Dict		=None
       if os.path.isdir(training_args.output_dir     ) and training_args.do_train and not training_args.overwrite_output_dir:
              _lowerCamelCase       :		List[str]		=get_last_checkpoint(training_args.output_dir     )
              if last_checkpoint is None and len(os.listdir(training_args.output_dir     )     ) > 0:
                     raise ValueError(
                         F'''Output directory ({training_args.output_dir}) already exists and is not empty. '''
                         'Use --overwrite_output_dir to overcome.'     )
              elif last_checkpoint is not None:
                     logger.info(
                         F'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '''
                         'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'     )

    # Setup logging
       logging.basicConfig(
           format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'		,			datefmt='%m/%d/%Y %H:%M:%S'		,			handlers=[logging.StreamHandler(sys.stdout     )]		,			)
       logger.setLevel(logging.INFO if is_main_process(training_args.local_rank     ) else logging.WARN     )

       # Log on each process the small summary:
       logger.warning(
           F'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}'''
           + F'''distributed training: {bool(training_args.local_rank != -1     )}, 16-bits training: {training_args.fpaa}'''     )
       # Set the verbosity to info of the Transformers logger (on main process only):
       if is_main_process(training_args.local_rank     ):
              transformers.utils.logging.set_verbosity_info()
       logger.info('Training/evaluation parameters %s'		,			SCREAMING_SNAKE_CASE__     )

       # Set seed before initializing model.
       set_seed(training_args.seed     )

       # Get the datasets:
       _lowerCamelCase       :		str		=datasets.load_dataset(
           'common_voice'		,			data_args.dataset_config_name		,			split=data_args.train_split_name     )
       _lowerCamelCase       :		int		=datasets.load_dataset('common_voice'		,			data_args.dataset_config_name		,			split='test'     )

       # Create and save tokenizer
       _lowerCamelCase       :		Dict		=F'''[{''.join(data_args.chars_to_ignore     )}]'''

       def remove_special_characters(SCREAMING_SNAKE_CASE__					:      Tuple     ):
              _lowerCamelCase       :		Optional[Any]		=re.sub(SCREAMING_SNAKE_CASE__		,			''		,			batch['sentence']     ).lower() + ' '
              return batch

       _lowerCamelCase       :		int		=train_dataset.map(SCREAMING_SNAKE_CASE__		,			remove_columns=['sentence']     )
       _lowerCamelCase       :		Tuple		=eval_dataset.map(SCREAMING_SNAKE_CASE__		,			remove_columns=['sentence']     )

       def extract_all_chars(SCREAMING_SNAKE_CASE__					:      Tuple     ):
              _lowerCamelCase       :		int		=' '.join(batch['text']     )
              _lowerCamelCase       :		Union[str, Any]		=list(set(SCREAMING_SNAKE_CASE__     )     )
              return {"vocab": [vocab], "all_text": [all_text]}

       _lowerCamelCase       :		Tuple		=train_dataset.map(
           SCREAMING_SNAKE_CASE__		,			batched=SCREAMING_SNAKE_CASE__		,			batch_size=-1		,			keep_in_memory=SCREAMING_SNAKE_CASE__		,			remove_columns=train_dataset.column_names		,			)
       _lowerCamelCase       :		Union[str, Any]		=train_dataset.map(
           SCREAMING_SNAKE_CASE__		,			batched=SCREAMING_SNAKE_CASE__		,			batch_size=-1		,			keep_in_memory=SCREAMING_SNAKE_CASE__		,			remove_columns=eval_dataset.column_names		,			)

       _lowerCamelCase       :		Optional[int]		=list(set(vocab_train['vocab'][0]     ) | set(vocab_test['vocab'][0]     )     )
       _lowerCamelCase       :		Tuple		={v: k for k, v in enumerate(SCREAMING_SNAKE_CASE__     )}
       _lowerCamelCase       :		int		=vocab_dict[' ']
       del vocab_dict[" "]
       _lowerCamelCase       :		Optional[Any]		=len(SCREAMING_SNAKE_CASE__     )
       _lowerCamelCase       :		int		=len(SCREAMING_SNAKE_CASE__     )

       with open('vocab.json'		,			'w'     ) as vocab_file:
              json.dump(SCREAMING_SNAKE_CASE__		,			SCREAMING_SNAKE_CASE__     )

       # Load pretrained model and tokenizer
       #
       # Distributed training:
       # The .from_pretrained methods guarantee that only one local process can concurrently
       # download model & vocab.
       _lowerCamelCase       :		int		=WavaVecaCTCTokenizer(
           'vocab.json'		,			unk_token='[UNK]'		,			pad_token='[PAD]'		,			word_delimiter_token='|'		,			)
       _lowerCamelCase       :		Optional[int]		=WavaVecaFeatureExtractor(
           feature_size=1		,			sampling_rate=16_000		,			padding_value=0.0		,			do_normalize=SCREAMING_SNAKE_CASE__		,			return_attention_mask=SCREAMING_SNAKE_CASE__     )
       _lowerCamelCase       :		Optional[int]		=WavaVecaProcessor(feature_extractor=SCREAMING_SNAKE_CASE__		,			tokenizer=SCREAMING_SNAKE_CASE__     )
       _lowerCamelCase       :		Any		=WavaVecaForCTC.from_pretrained(
           model_args.model_name_or_path		,			cache_dir=model_args.cache_dir		,			activation_dropout=model_args.activation_dropout		,			attention_dropout=model_args.attention_dropout		,			hidden_dropout=model_args.hidden_dropout		,			feat_proj_dropout=model_args.feat_proj_dropout		,			mask_time_prob=model_args.mask_time_prob		,			gradient_checkpointing=training_args.gradient_checkpointing		,			layerdrop=model_args.layerdrop		,			ctc_loss_reduction='mean'		,			pad_token_id=processor.tokenizer.pad_token_id		,			vocab_size=len(processor.tokenizer     )		,			)

       if data_args.max_train_samples is not None:
              _lowerCamelCase       :		List[str]		=min(len(SCREAMING_SNAKE_CASE__     )		,			data_args.max_train_samples     )
              _lowerCamelCase       :		Any		=train_dataset.select(range(SCREAMING_SNAKE_CASE__     )     )

       if data_args.max_val_samples is not None:
              _lowerCamelCase       :		Optional[int]		=eval_dataset.select(range(data_args.max_val_samples     )     )

       _lowerCamelCase       :		str		=torchaudio.transforms.Resample(48_000		,			16_000     )

       # Preprocessing the datasets.
       # We need to read the aduio files as arrays and tokenize the targets.
       def speech_file_to_array_fn(SCREAMING_SNAKE_CASE__					:      List[Any]     ):
              _lowerCamelCase	,     _lowerCamelCase       :		Tuple		=torchaudio.load(batch['path']     )
              _lowerCamelCase       :		Optional[int]		=resampler(SCREAMING_SNAKE_CASE__     ).squeeze().numpy()
              _lowerCamelCase       :		Optional[Any]		=16_000
              _lowerCamelCase       :		Tuple		=batch['text']
              return batch

       _lowerCamelCase       :		Any		=train_dataset.map(
           SCREAMING_SNAKE_CASE__		,			remove_columns=train_dataset.column_names		,			num_proc=data_args.preprocessing_num_workers		,			)
       _lowerCamelCase       :		Optional[int]		=eval_dataset.map(
           SCREAMING_SNAKE_CASE__		,			remove_columns=eval_dataset.column_names		,			num_proc=data_args.preprocessing_num_workers		,			)

       def prepare_dataset(SCREAMING_SNAKE_CASE__					:      Union[str, Any]     ):
              # check that all files have the correct sampling rate
              assert (
                  len(set(batch['sampling_rate']     )     ) == 1
              ), F'''Make sure all inputs have the same sampling rate of {processor.feature_extractor.sampling_rate}.'''

              _lowerCamelCase       :		int		=processor(
                  audio=batch['speech']		,			text=batch['target_text']		,			sampling_rate=batch['sampling_rate'][0]     )
              batch.update(SCREAMING_SNAKE_CASE__     )
              return batch

       _lowerCamelCase       :		str		=train_dataset.map(
           SCREAMING_SNAKE_CASE__		,			remove_columns=train_dataset.column_names		,			batch_size=training_args.per_device_train_batch_size		,			batched=SCREAMING_SNAKE_CASE__		,			num_proc=data_args.preprocessing_num_workers		,			)
       _lowerCamelCase       :		Tuple		=eval_dataset.map(
           SCREAMING_SNAKE_CASE__		,			remove_columns=eval_dataset.column_names		,			batch_size=training_args.per_device_train_batch_size		,			batched=SCREAMING_SNAKE_CASE__		,			num_proc=data_args.preprocessing_num_workers		,			)

       # Metric
       _lowerCamelCase       :		Union[str, Any]		=datasets.load_metric('wer'     )

       def compute_metrics(SCREAMING_SNAKE_CASE__					:      str     ):
              _lowerCamelCase       :		Union[str, Any]		=pred.predictions
              _lowerCamelCase       :		Optional[int]		=np.argmax(SCREAMING_SNAKE_CASE__		,			axis=-1     )

              _lowerCamelCase       :		Any		=processor.tokenizer.pad_token_id

              _lowerCamelCase       :		Any		=processor.batch_decode(SCREAMING_SNAKE_CASE__     )
              # we do not want to group tokens when computing the metrics
              _lowerCamelCase       :		List[Any]		=processor.batch_decode(pred.label_ids		,			group_tokens=SCREAMING_SNAKE_CASE__     )

              _lowerCamelCase       :		Any		=wer_metric.compute(predictions=SCREAMING_SNAKE_CASE__		,			references=SCREAMING_SNAKE_CASE__     )

              return {"wer": wer}

       if model_args.freeze_feature_extractor:
              model.freeze_feature_extractor()

       # Data collator
       _lowerCamelCase       :		Optional[int]		=DataCollatorCTCWithPadding(processor=SCREAMING_SNAKE_CASE__		,			padding=SCREAMING_SNAKE_CASE__     )

       # Initialize our Trainer
       _lowerCamelCase       :		Optional[Any]		=CTCTrainer(
           model=SCREAMING_SNAKE_CASE__		,			data_collator=SCREAMING_SNAKE_CASE__		,			args=SCREAMING_SNAKE_CASE__		,			compute_metrics=SCREAMING_SNAKE_CASE__		,			train_dataset=train_dataset if training_args.do_train else None		,			eval_dataset=eval_dataset if training_args.do_eval else None		,			tokenizer=processor.feature_extractor		,			)

       # Training
       if training_args.do_train:
              if last_checkpoint is not None:
                     _lowerCamelCase       :		Optional[Any]		=last_checkpoint
              elif os.path.isdir(model_args.model_name_or_path     ):
                     _lowerCamelCase       :		Dict		=model_args.model_name_or_path
              else:
                     _lowerCamelCase       :		int		=None

              # Save the feature_extractor and the tokenizer
              if is_main_process(training_args.local_rank     ):
                     processor.save_pretrained(training_args.output_dir     )

              _lowerCamelCase       :		Optional[int]		=trainer.train(resume_from_checkpoint=SCREAMING_SNAKE_CASE__     )
              trainer.save_model()

              _lowerCamelCase       :		Any		=train_result.metrics
              _lowerCamelCase       :		Optional[int]		=(
                  data_args.max_train_samples if data_args.max_train_samples is not None else len(SCREAMING_SNAKE_CASE__     )
              )
              _lowerCamelCase       :		List[Any]		=min(SCREAMING_SNAKE_CASE__		,			len(SCREAMING_SNAKE_CASE__     )     )

              trainer.log_metrics('train'		,			SCREAMING_SNAKE_CASE__     )
              trainer.save_metrics('train'		,			SCREAMING_SNAKE_CASE__     )
              trainer.save_state()

       # Evaluation
       _lowerCamelCase       :		str		={}
       if training_args.do_eval:
              logger.info('*** Evaluate ***'     )
              _lowerCamelCase       :		Tuple		=trainer.evaluate()
              _lowerCamelCase       :		List[Any]		=data_args.max_val_samples if data_args.max_val_samples is not None else len(SCREAMING_SNAKE_CASE__     )
              _lowerCamelCase       :		Union[str, Any]		=min(SCREAMING_SNAKE_CASE__		,			len(SCREAMING_SNAKE_CASE__     )     )

              trainer.log_metrics('eval'		,			SCREAMING_SNAKE_CASE__     )
              trainer.save_metrics('eval'		,			SCREAMING_SNAKE_CASE__     )

       return results


if __name__ == "__main__":
 main()


