
'''simple docstring'''


import itertools
import random
import unittest

import numpy as np

from transformers import ASTFeatureExtractor
from transformers.testing_utils import require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


__lowercase							:   Optional[Any]					=     random.Random()

if is_torch_available():
					import torch




def lowercase_	(   _lowercase			,       _lowercase=1.0			,       _lowercase=None			,       _lowercase=None				)     ->							Dict:
					'''simple docstring'''

					if rng is None:
										lowerCamelCase_					:      Tuple     =		global_rng

					lowerCamelCase_					:      int     =		[]
					for batch_idx in range(shape[0]				):
										values.append([]				)
										for _ in range(shape[1]				):
															values[-1].append(rng.random() * scale				)

					return values

class 	__lowercase				(  unittest.TestCase    ):

			def __init__(self			,   A			,   A=7			,   A=4_0_0			,   A=2_0_0_0			,   A=1			,   A=0.0			,   A=1_6_0_0_0			,   A=True			,   A=True			,   ):
								lowerCamelCase_					:      Any     =		parent
								lowerCamelCase_					:      Union[str, Any]     =		batch_size
								lowerCamelCase_					:      Tuple     =		min_seq_length
								lowerCamelCase_					:      Any     =		max_seq_length
								lowerCamelCase_					:      Any     =		(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
								lowerCamelCase_					:      List[Any]     =		feature_size
								lowerCamelCase_					:      int     =		padding_value
								lowerCamelCase_					:      Optional[Any]     =		sampling_rate
								lowerCamelCase_					:      Tuple     =		return_attention_mask
								lowerCamelCase_					:      List[Any]     =		do_normalize

			def        UpperCAmelCase__ (self      ):
								return {
								    "feature_size": self.feature_size,
								    "padding_value": self.padding_value,
								    "sampling_rate": self.sampling_rate,
								    "return_attention_mask": self.return_attention_mask,
								    "do_normalize": self.do_normalize,
								}






			def        UpperCAmelCase__ (self			,   A=False			,   A=False      ):
								def _flatten(A      ):
													return list(itertools.chain(*A      )      )

								if equal_length:
													lowerCamelCase_					:      List[str]     =		floats_list((self.batch_size, self.max_seq_length)      )
								else:
													# make sure that inputs increase in size
													lowerCamelCase_					:      int     =		[
													    _flatten(floats_list((x, self.feature_size)      )      )
													    for x in range(self.min_seq_length			,   self.max_seq_length			,   self.seq_length_diff      )
													]

								if numpify:
													lowerCamelCase_					:      List[str]     =		[np.asarray(A      ) for x in speech_inputs]

								return speech_inputs

@require_torch
@require_torchaudio
class 	__lowercase				(  _lowercase      ,     unittest.TestCase    ):
			lowerCamelCase			:		List[str]	      =			ASTFeatureExtractor

			def        UpperCAmelCase__ (self      ):
								lowerCamelCase_					:      Union[str, Any]     =		ASTFeatureExtractionTester(self      )

			def        UpperCAmelCase__ (self      ):
								# Tests that all call wrap to encode_plus and batch_encode_plus
								lowerCamelCase_					:      Union[str, Any]     =		self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()      )
								# create three inputs of length 800, 1000, and 1200
								lowerCamelCase_					:      Optional[Any]     =		[floats_list((1, x)      )[0] for x in range(8_0_0			,   1_4_0_0			,   2_0_0      )]
								lowerCamelCase_					:      List[Any]     =		[np.asarray(A      ) for speech_input in speech_inputs]

								# Test not batched input
								lowerCamelCase_					:      Any     =		feat_extract(speech_inputs[0]			,   return_tensors='''np'''      ).input_values
								lowerCamelCase_					:      Dict     =		feat_extract(np_speech_inputs[0]			,   return_tensors='''np'''      ).input_values
								self.assertTrue(np.allclose(A			,   A			,   atol=1E-3      )      )

								# Test batched
								lowerCamelCase_					:      Any     =		feat_extract(A			,   padding=A			,   return_tensors='''np'''      ).input_values
								lowerCamelCase_					:      str     =		feat_extract(A			,   padding=A			,   return_tensors='''np'''      ).input_values
								for enc_seq_a, enc_seq_a in zip(A			,   A      ):
													self.assertTrue(np.allclose(A			,   A			,   atol=1E-3      )      )

								# Test 2-D numpy arrays are batched.
								lowerCamelCase_					:      Any     =		[floats_list((1, x)      )[0] for x in (8_0_0, 8_0_0, 8_0_0)]
								lowerCamelCase_					:      Optional[int]     =		np.asarray(A      )
								lowerCamelCase_					:      Union[str, Any]     =		feat_extract(A			,   return_tensors='''np'''      ).input_values
								lowerCamelCase_					:      int     =		feat_extract(A			,   return_tensors='''np'''      ).input_values
								for enc_seq_a, enc_seq_a in zip(A			,   A      ):
													self.assertTrue(np.allclose(A			,   A			,   atol=1E-3      )      )

			@require_torch
			def        UpperCAmelCase__ (self      ):
								import torch

								lowerCamelCase_					:      Optional[Any]     =		self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()      )
								lowerCamelCase_					:      Dict     =		np.random.rand(1_0_0      ).astype(np.floataa      )
								lowerCamelCase_					:      List[Any]     =		np_speech_inputs.tolist()

								for inputs in [py_speech_inputs, np_speech_inputs]:
													lowerCamelCase_					:      Tuple     =		feature_extractor.pad([{'''input_values''': inputs}]			,   return_tensors='''np'''      )
													self.assertTrue(np_processed.input_values.dtype == np.floataa      )
													lowerCamelCase_					:      Optional[int]     =		feature_extractor.pad([{'''input_values''': inputs}]			,   return_tensors='''pt'''      )
													self.assertTrue(pt_processed.input_values.dtype == torch.floataa      )

			def        UpperCAmelCase__ (self			,   A      ):
								from datasets import load_dataset

								lowerCamelCase_					:      Dict     =		load_dataset('''hf-internal-testing/librispeech_asr_dummy'''			,   '''clean'''			,   split='''validation'''      )
								# automatic decoding with librispeech
								lowerCamelCase_					:      Optional[Any]     =		ds.sort('''id'''      ).select(range(A      )      )[:num_samples]['''audio''']

								return [x["array"] for x in speech_samples]






			@require_torch
			def        UpperCAmelCase__ (self      ):
								# fmt: off
								lowerCamelCase_					:      Union[str, Any]     =		torch.tensor(
								    [-0.98_94, -1.27_76, -0.90_66, -1.27_76, -0.93_49, -1.26_09, -1.03_86, -1.27_76,
								     -1.15_61, -1.27_76, -1.20_52, -1.27_23, -1.21_90, -1.21_32, -1.27_76, -1.11_33,
								     -1.19_53, -1.13_43, -1.15_84, -1.22_03, -1.17_70, -1.24_74, -1.23_81, -1.19_36,
								     -0.92_70, -0.83_17, -0.80_49, -0.77_06, -0.75_65, -0.78_69]      )
								# fmt: on

								lowerCamelCase_					:      str     =		self._load_datasamples(1      )
								lowerCamelCase_					:      str     =		ASTFeatureExtractor()
								lowerCamelCase_					:      Tuple     =		feature_extractor(A			,   return_tensors='''pt'''      ).input_values
								self.assertEquals(input_values.shape			,   (1, 1_0_2_4, 1_2_8)      )
								self.assertTrue(torch.allclose(input_values[0, 0, :3_0]			,   A			,   atol=1E-4      )      )

'''simple docstring'''


import asyncio
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from distutils.util import strtobool
from functools import partial
from pathlib import Path
from typing import List, Union
from unittest import mock

import torch

from ..state import AcceleratorState, PartialState
from ..utils import (
    gather,
    is_bnb_available,
    is_comet_ml_available,
    is_datasets_available,
    is_deepspeed_available,
    is_mps_available,
    is_safetensors_available,
    is_tensorboard_available,
    is_torch_version,
    is_tpu_available,
    is_transformers_available,
    is_wandb_available,
    is_xpu_available,
)




def lowercase_	(   _lowercase			,       _lowercase=False				)     ->							int:
					'''simple docstring'''

					try:
										lowerCamelCase_					:      Union[str, Any]     =		os.environ[key]
					except KeyError:
										# KEY isn't set, default to `default`.
										lowerCamelCase_					:      Union[str, Any]     =		default
					else:
										# KEY is set, convert it to True or False.
										try:
															lowerCamelCase_					:      List[str]     =		strtobool(_lowercase				)
										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


__lowercase							:   Union[str, Any]					=     parse_flag_from_env('''RUN_SLOW''', default=False)




def lowercase_	(   _lowercase				)     ->							Union[str, Any]:
					'''simple docstring'''

					return unittest.skip('''Test was skipped'''				)(_lowercase				)




def lowercase_	(   _lowercase				)     ->							Optional[Any]:
					'''simple docstring'''

					return unittest.skipUnless(_run_slow_tests			,       '''test is slow'''				)(_lowercase				)




def lowercase_	(   _lowercase				)     ->							List[str]:
					'''simple docstring'''

					return unittest.skipUnless(not torch.cuda.is_available()			,       '''test requires only a CPU'''				)(_lowercase				)




def lowercase_	(   _lowercase				)     ->							str:
					'''simple docstring'''

					return unittest.skipUnless(torch.cuda.is_available()			,       '''test requires a GPU'''				)(_lowercase				)




def lowercase_	(   _lowercase				)     ->							str:
					'''simple docstring'''

					return unittest.skipUnless(is_xpu_available()			,       '''test requires a XPU'''				)(_lowercase				)




def lowercase_	(   _lowercase				)     ->							List[str]:
					'''simple docstring'''

					return unittest.skipUnless(is_mps_available()			,       '''test requires a `mps` backend support in `torch`'''				)(_lowercase				)




def lowercase_	(   _lowercase				)     ->							Tuple:
					'''simple docstring'''

					return unittest.skipUnless(
					    is_transformers_available() and is_datasets_available()			,       '''test requires the Hugging Face suite'''				)(_lowercase				)




def lowercase_	(   _lowercase				)     ->							Tuple:
					'''simple docstring'''

					return unittest.skipUnless(is_bnb_available()			,       '''test requires the bitsandbytes library'''				)(_lowercase				)




def lowercase_	(   _lowercase				)     ->							Union[str, Any]:
					'''simple docstring'''

					return unittest.skipUnless(is_tpu_available()			,       '''test requires TPU'''				)(_lowercase				)




def lowercase_	(   _lowercase				)     ->							Union[str, Any]:
					'''simple docstring'''

					return unittest.skipUnless(torch.cuda.device_count() == 1			,       '''test requires a GPU'''				)(_lowercase				)




def lowercase_	(   _lowercase				)     ->							List[str]:
					'''simple docstring'''

					return unittest.skipUnless(torch.xpu.device_count() == 1			,       '''test requires a XPU'''				)(_lowercase				)




def lowercase_	(   _lowercase				)     ->							Tuple:
					'''simple docstring'''

					return unittest.skipUnless(torch.cuda.device_count() > 1			,       '''test requires multiple GPUs'''				)(_lowercase				)




def lowercase_	(   _lowercase				)     ->							str:
					'''simple docstring'''

					return unittest.skipUnless(torch.xpu.device_count() > 1			,       '''test requires multiple XPUs'''				)(_lowercase				)




def lowercase_	(   _lowercase				)     ->							Tuple:
					'''simple docstring'''

					return unittest.skipUnless(is_safetensors_available()			,       '''test requires safetensors'''				)(_lowercase				)




def lowercase_	(   _lowercase				)     ->							int:
					'''simple docstring'''

					return unittest.skipUnless(is_deepspeed_available()			,       '''test requires DeepSpeed'''				)(_lowercase				)




def lowercase_	(   _lowercase				)     ->							Union[str, Any]:
					'''simple docstring'''

					return unittest.skipUnless(is_torch_version('''>='''			,       '''1.12.0'''				)			,       '''test requires torch version >= 1.12.0'''				)(_lowercase				)




def lowercase_	(   _lowercase=None			,       _lowercase=None				)     ->							Any:
					'''simple docstring'''

					if test_case is None:
										return partial(_lowercase			,       version=_lowercase				)
					return unittest.skipUnless(is_torch_version('''>='''			,       _lowercase				)			,       F"""test requires torch version >= {version}"""				)(_lowercase				)




def lowercase_	(   _lowercase				)     ->							str:
					'''simple docstring'''

					return unittest.skipUnless(is_tensorboard_available()			,       '''test requires Tensorboard'''				)(_lowercase				)




def lowercase_	(   _lowercase				)     ->							Union[str, Any]:
					'''simple docstring'''

					return unittest.skipUnless(is_wandb_available()			,       '''test requires wandb'''				)(_lowercase				)




def lowercase_	(   _lowercase				)     ->							int:
					'''simple docstring'''

					return unittest.skipUnless(is_comet_ml_available()			,       '''test requires comet_ml'''				)(_lowercase				)


__lowercase							:   str					=     (
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)




def lowercase_	(   _lowercase				)     ->							List[Any]:
					'''simple docstring'''

					return unittest.skipUnless(
					    _atleast_one_tracker_available			,       '''test requires at least one tracker to be available and for `comet_ml` to not be installed'''			,       )(_lowercase				)

class 	__lowercase				(  unittest.TestCase    ):
			lowerCamelCase			:		Optional[Any]	      =			True

			@classmethod
			def        UpperCAmelCase__ (cls      ):
								lowerCamelCase_					:      Optional[Any]     =		tempfile.mkdtemp()

			@classmethod
			def        UpperCAmelCase__ (cls      ):
								if os.path.exists(cls.tmpdir      ):
													shutil.rmtree(cls.tmpdir      )






			def        UpperCAmelCase__ (self      ):
								if self.clear_on_setup:
													for path in Path(self.tmpdir      ).glob('''**/*'''      ):
																		if path.is_file():
																							path.unlink()
																		elif path.is_dir():
																							shutil.rmtree(A      )

class 	__lowercase				(  unittest.TestCase    ):

			def        UpperCAmelCase__ (self      ):
								super().tearDown()
								# Reset the state of the AcceleratorState singleton.
								AcceleratorState._reset_state()
								PartialState._reset_state()

class 	__lowercase				(  unittest.TestCase    ):

			def        UpperCAmelCase__ (self			,   A      ):
								lowerCamelCase_					:      List[str]     =		mocks if isinstance(A			,   (tuple, list)      ) else [mocks]
								for m in self.mocks:
													m.start()
													self.addCleanup(m.stop      )




def lowercase_	(   _lowercase				)     ->							Optional[int]:
					'''simple docstring'''

					lowerCamelCase_					:      Tuple     =		AcceleratorState()
					lowerCamelCase_					:      Optional[Any]     =		tensor[None].clone().to(state.device				)
					lowerCamelCase_					:      Dict     =		gather(_lowercase				).cpu()
					lowerCamelCase_					:      List[str]     =		tensor[0].cpu()
					for i in range(tensors.shape[0]				):
										if not torch.equal(tensors[i]			,       _lowercase				):
															return False
					return True

class 	__lowercase				:

			def __init__(self			,   A			,   A			,   A      ):
								lowerCamelCase_					:      List[Any]     =		returncode
								lowerCamelCase_					:      Optional[int]     =		stdout
								lowerCamelCase_					:      List[str]     =		stderr




async def lowercase_	(   _lowercase			,       _lowercase				)     ->							Tuple:
					'''simple docstring'''

					while True:
										lowerCamelCase_					:      Any     =		await stream.readline()
										if line:
															callback(_lowercase				)
										else:
															break




async def lowercase_	(   _lowercase			,       _lowercase=None			,       _lowercase=None			,       _lowercase=None			,       _lowercase=False			,       _lowercase=False				)     ->							_RunOutput:
					'''simple docstring'''

					if echo:
										print('''\nRunning: '''			,       ''' '''.join(_lowercase				)				)

					lowerCamelCase_					:      Any     =		await asyncio.create_subprocess_exec(
					    cmd[0]			,       *cmd[1:]			,       stdin=_lowercase			,       stdout=asyncio.subprocess.PIPE			,       stderr=asyncio.subprocess.PIPE			,       env=_lowercase			,       )

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

					lowerCamelCase_					:      List[Any]     =		[]
					lowerCamelCase_					:      Optional[int]     =		[]

					def tee(_lowercase			,       _lowercase			,       _lowercase			,       _lowercase=""				):
										lowerCamelCase_					:      Union[str, Any]     =		line.decode('''utf-8'''				).rstrip()
										sink.append(_lowercase				)
										if not quiet:
															print(_lowercase			,       _lowercase			,       file=_lowercase				)

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




def lowercase_	(   _lowercase			,       _lowercase=None			,       _lowercase=None			,       _lowercase=180			,       _lowercase=False			,       _lowercase=True				)     ->							_RunOutput:
					'''simple docstring'''

					lowerCamelCase_					:      Any     =		asyncio.get_event_loop()
					lowerCamelCase_					:      List[str]     =		loop.run_until_complete(
					    _stream_subprocess(_lowercase			,       env=_lowercase			,       stdin=_lowercase			,       timeout=_lowercase			,       quiet=_lowercase			,       echo=_lowercase				)				)

					lowerCamelCase_					:      List[Any]     =		''' '''.join(_lowercase				)
					if result.returncode > 0:
										lowerCamelCase_					:      Optional[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}"""				)

					return result

class 	__lowercase				(  _lowercase    ):
			pass




def lowercase_	(   _lowercase			,       _lowercase=False				)     ->							Dict:
					'''simple docstring'''

					try:
										lowerCamelCase_					:      List[str]     =		subprocess.check_output(_lowercase			,       stderr=subprocess.STDOUT				)
										if return_stdout:
															if hasattr(_lowercase			,       '''decode'''				):
																				lowerCamelCase_					:      str     =		output.decode('''utf-8'''				)
															return output
					except subprocess.CalledProcessError as e:
										raise SubprocessCallException(
										    F"""Command `{" ".join(_lowercase				)}` failed with the following error:\n\n{e.output.decode()}"""				) from e


