


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


__SCREAMING_SNAKE_CASE							:    List[Any]		=    parse_flag_from_env('RUN_SLOW', default=False)







def 						_a				(      _SCREAMING_SNAKE_CASE				)    ->				List[Any]:
							return unittest.skip("""Test was skipped"""				)(_SCREAMING_SNAKE_CASE				)







def 						_a				(      _SCREAMING_SNAKE_CASE				)    ->				Union[str, Any]:
							return unittest.skipUnless(_run_slow_tests				, """test is slow"""				)(_SCREAMING_SNAKE_CASE				)







def 						_a				(      _SCREAMING_SNAKE_CASE				)    ->				int:
							return unittest.skipUnless(not torch.cuda.is_available()				, """test requires only a CPU"""				)(_SCREAMING_SNAKE_CASE				)







def 						_a				(      _SCREAMING_SNAKE_CASE				)    ->				Optional[Any]:
							return unittest.skipUnless(torch.cuda.is_available()				, """test requires a GPU"""				)(_SCREAMING_SNAKE_CASE				)







def 						_a				(      _SCREAMING_SNAKE_CASE				)    ->				Optional[int]:
							return unittest.skipUnless(is_xpu_available()				, """test requires a XPU"""				)(_SCREAMING_SNAKE_CASE				)







def 						_a				(      _SCREAMING_SNAKE_CASE				)    ->				Optional[Any]:
							return unittest.skipUnless(is_mps_available()				, """test requires a `mps` backend support in `torch`"""				)(_SCREAMING_SNAKE_CASE				)







def 						_a				(      _SCREAMING_SNAKE_CASE				)    ->				Any:
							return unittest.skipUnless(
							    is_transformers_available() and is_datasets_available()				, """test requires the Hugging Face suite"""				)(_SCREAMING_SNAKE_CASE				)







def 						_a				(      _SCREAMING_SNAKE_CASE				)    ->				Optional[Any]:
							return unittest.skipUnless(is_bnb_available()				, """test requires the bitsandbytes library"""				)(_SCREAMING_SNAKE_CASE				)







def 						_a				(      _SCREAMING_SNAKE_CASE				)    ->				str:
							return unittest.skipUnless(is_tpu_available()				, """test requires TPU"""				)(_SCREAMING_SNAKE_CASE				)







def 						_a				(      _SCREAMING_SNAKE_CASE				)    ->				Any:
							return unittest.skipUnless(torch.cuda.device_count() == 1				, """test requires a GPU"""				)(_SCREAMING_SNAKE_CASE				)







def 						_a				(      _SCREAMING_SNAKE_CASE				)    ->				Any:
							return unittest.skipUnless(torch.xpu.device_count() == 1				, """test requires a XPU"""				)(_SCREAMING_SNAKE_CASE				)







def 						_a				(      _SCREAMING_SNAKE_CASE				)    ->				Any:
							return unittest.skipUnless(torch.cuda.device_count() > 1				, """test requires multiple GPUs"""				)(_SCREAMING_SNAKE_CASE				)







def 						_a				(      _SCREAMING_SNAKE_CASE				)    ->				str:
							return unittest.skipUnless(torch.xpu.device_count() > 1				, """test requires multiple XPUs"""				)(_SCREAMING_SNAKE_CASE				)







def 						_a				(      _SCREAMING_SNAKE_CASE				)    ->				Tuple:
							return unittest.skipUnless(is_safetensors_available()				, """test requires safetensors"""				)(_SCREAMING_SNAKE_CASE				)







def 						_a				(      _SCREAMING_SNAKE_CASE				)    ->				str:
							return unittest.skipUnless(is_deepspeed_available()				, """test requires DeepSpeed"""				)(_SCREAMING_SNAKE_CASE				)







def 						_a				(      _SCREAMING_SNAKE_CASE				)    ->				Any:
							return unittest.skipUnless(is_torch_version(""">="""				, """1.12.0"""				)				, """test requires torch version >= 1.12.0"""				)(_SCREAMING_SNAKE_CASE				)







def 						_a				(      _SCREAMING_SNAKE_CASE=None				, _SCREAMING_SNAKE_CASE=None				)    ->				Union[str, Any]:
							if test_case is None:
														return partial(_SCREAMING_SNAKE_CASE				, version=_SCREAMING_SNAKE_CASE				)
							return unittest.skipUnless(is_torch_version(""">="""				, _SCREAMING_SNAKE_CASE				)				, f"""test requires torch version >= {version}"""				)(_SCREAMING_SNAKE_CASE				)







def 						_a				(      _SCREAMING_SNAKE_CASE				)    ->				List[str]:
							return unittest.skipUnless(is_tensorboard_available()				, """test requires Tensorboard"""				)(_SCREAMING_SNAKE_CASE				)







def 						_a				(      _SCREAMING_SNAKE_CASE				)    ->				Tuple:
							return unittest.skipUnless(is_wandb_available()				, """test requires wandb"""				)(_SCREAMING_SNAKE_CASE				)







def 						_a				(      _SCREAMING_SNAKE_CASE				)    ->				Dict:
							return unittest.skipUnless(is_comet_ml_available()				, """test requires comet_ml"""				)(_SCREAMING_SNAKE_CASE				)


__SCREAMING_SNAKE_CASE							:    Any		=    (
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)







def 						_a				(      _SCREAMING_SNAKE_CASE				)    ->				Union[str, Any]:
							return unittest.skipUnless(
							    _atleast_one_tracker_available				, """test requires at least one tracker to be available and for `comet_ml` to not be installed"""				, )(_SCREAMING_SNAKE_CASE				)





class      __A     (unittest.TestCase):





							'''simple docstring'''

							__lowercase:		Tuple							      =    True



							@classmethod
							def 		lowerCAmelCase       (				cls							:      Tuple       )					->str:



														"""simple docstring"""



														snake_case_           =		tempfile.mkdtemp()



							@classmethod
							def 		lowerCAmelCase       (				cls							:      Tuple       )					->Any:



														"""simple docstring"""



														if os.path.exists(cls.tmpdir       ):
																					shutil.rmtree(cls.tmpdir       )



							def 		lowerCAmelCase       (				self							:      int       )					->Optional[Any]:



														"""simple docstring"""



														if self.clear_on_setup:
																					for path in Path(self.tmpdir       ).glob("""**/*"""       ):
																												if path.is_file():
																																			path.unlink()
																												elif path.is_dir():
																																			shutil.rmtree(UpperCAmelCase_       )





class      __A     (unittest.TestCase):





							'''simple docstring'''

							def 		lowerCAmelCase       (				self							:      Tuple       )					->Optional[Any]:



														"""simple docstring"""



														super().tearDown()
														# Reset the state of the AcceleratorState singleton.
														AcceleratorState._reset_state()
														PartialState._reset_state()





class      __A     (unittest.TestCase):





							'''simple docstring'''

							def 		lowerCAmelCase       (				self							:      Optional[Any]		,       UpperCAmelCase_							:      Union[mock.Mock, List[mock.Mock]]       )					->str:



														"""simple docstring"""



														snake_case_           =		mocks if isinstance(UpperCAmelCase_		,       (tuple, list)       ) else [mocks]
														for m in self.mocks:
																					m.start()
																					self.addCleanup(m.stop       )







def 						_a				(      _SCREAMING_SNAKE_CASE				)    ->				List[Any]:
							snake_case_           =		AcceleratorState()
							snake_case_           =		tensor[None].clone().to(state.device				)
							snake_case_           =		gather(_SCREAMING_SNAKE_CASE				).cpu()
							snake_case_           =		tensor[0].cpu()
							for i in range(tensors.shape[0]				):
														if not torch.equal(tensors[i]				, _SCREAMING_SNAKE_CASE				):
																					return False
							return True





class      __A     :





							'''simple docstring'''

							def __init__(				self							:      Optional[Any]		,       UpperCAmelCase_							:      str		,       UpperCAmelCase_							:      Any		,       UpperCAmelCase_							:      int       )					->Any:



														"""simple docstring"""



														snake_case_           =		returncode
														snake_case_           =		stdout
														snake_case_           =		stderr







async def 						_a				(      _SCREAMING_SNAKE_CASE				, _SCREAMING_SNAKE_CASE				)    ->				str:
							while True:
														snake_case_           =		await stream.readline()
														if line:
																					callback(_SCREAMING_SNAKE_CASE				)
														else:
																					break







async def 						_a				(      _SCREAMING_SNAKE_CASE				, _SCREAMING_SNAKE_CASE=None				, _SCREAMING_SNAKE_CASE=None				, _SCREAMING_SNAKE_CASE=None				, _SCREAMING_SNAKE_CASE=False				, _SCREAMING_SNAKE_CASE=False				)    ->				_RunOutput:
							if echo:
														print("""\nRunning: """				, """ """.join(_SCREAMING_SNAKE_CASE				)				)

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

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

							snake_case_           =		[]
							snake_case_           =		[]

							def tee(_SCREAMING_SNAKE_CASE				, _SCREAMING_SNAKE_CASE				, _SCREAMING_SNAKE_CASE				, _SCREAMING_SNAKE_CASE=""				):
														snake_case_           =		line.decode("""utf-8"""				).rstrip()
														sink.append(_SCREAMING_SNAKE_CASE				)
														if not quiet:
																					print(_SCREAMING_SNAKE_CASE				, _SCREAMING_SNAKE_CASE				, file=_SCREAMING_SNAKE_CASE				)

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







def 						_a				(      _SCREAMING_SNAKE_CASE				, _SCREAMING_SNAKE_CASE=None				, _SCREAMING_SNAKE_CASE=None				, _SCREAMING_SNAKE_CASE=180				, _SCREAMING_SNAKE_CASE=False				, _SCREAMING_SNAKE_CASE=True				)    ->				_RunOutput:
							snake_case_           =		asyncio.get_event_loop()
							snake_case_           =		loop.run_until_complete(
							    _stream_subprocess(_SCREAMING_SNAKE_CASE				, env=_SCREAMING_SNAKE_CASE				, stdin=_SCREAMING_SNAKE_CASE				, timeout=_SCREAMING_SNAKE_CASE				, quiet=_SCREAMING_SNAKE_CASE				, echo=_SCREAMING_SNAKE_CASE				)				)

							snake_case_           =		""" """.join(_SCREAMING_SNAKE_CASE				)
							if result.returncode > 0:
														snake_case_           =		"""\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      __A     (snake_case__):





							'''simple docstring'''

							pass







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







"""simple docstring"""
import copy
from dataclasses import dataclass, field
from typing import ClassVar, Dict

from ..features import Audio, Features, Value
from .base import TaskTemplate





@dataclass(frozen=snake_case__)
class      __A     (snake_case__):





							'''simple docstring'''

							__lowercase:		str							      =    field(default="""automatic-speech-recognition"""						,		metadata={"""include_in_asdict_even_if_is_default""": True})
							__lowercase:		ClassVar[Features]							      =    Features({"""audio""": Audio()})
							__lowercase:		ClassVar[Features]							      =    Features({"""transcription""": Value("""string""")})
							__lowercase:		str							      =    "audio"
							__lowercase:		str							      =    "transcription"



							def 		lowerCAmelCase       (				self							:      List[Any]		,       UpperCAmelCase_							:      Any       )					->int:



														"""simple docstring"""



														if self.audio_column not in features:
																					raise ValueError(F"""Column {self.audio_column} is not present in features."""       )
														if not isinstance(features[self.audio_column]		,       UpperCAmelCase_       ):
																					raise ValueError(F"""Column {self.audio_column} is not an Audio type."""       )
														snake_case_           =		copy.deepcopy(self       )
														snake_case_           =		self.input_schema.copy()
														snake_case_           =		features[self.audio_column]
														snake_case_           =		input_schema
														return task_template



							@property
							def 		lowerCAmelCase       (				self							:      List[str]       )					->Dict[str, str]:



														"""simple docstring"""



														return {self.audio_column: "audio", self.transcription_column: "transcription"}



