

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 						_snake_case(    SCREAMING_SNAKE_CASE__			:	Optional[Any]    ,			SCREAMING_SNAKE_CASE__			:	List[str]=False      )							->      Optional[int]:





    '''simple docstring'''






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


lowercase_       		=  parse_flag_from_env("RUN_SLOW", default=False)
def 						_snake_case(    SCREAMING_SNAKE_CASE__			:	List[Any]      )							->      Tuple:





    '''simple docstring'''






    return unittest.skip('Test was skipped'      )(SCREAMING_SNAKE_CASE__      )
def 						_snake_case(    SCREAMING_SNAKE_CASE__			:	List[Any]      )							->      Dict:





    '''simple docstring'''






    return unittest.skipUnless(_run_slow_tests    ,			'test is slow'      )(SCREAMING_SNAKE_CASE__      )
def 						_snake_case(    SCREAMING_SNAKE_CASE__			:	Union[str, Any]      )							->      Union[str, Any]:





    '''simple docstring'''






    return unittest.skipUnless(not torch.cuda.is_available()    ,			'test requires only a CPU'      )(SCREAMING_SNAKE_CASE__      )
def 						_snake_case(    SCREAMING_SNAKE_CASE__			:	List[Any]      )							->      Dict:





    '''simple docstring'''






    return unittest.skipUnless(torch.cuda.is_available()    ,			'test requires a GPU'      )(SCREAMING_SNAKE_CASE__      )
def 						_snake_case(    SCREAMING_SNAKE_CASE__			:	List[str]      )							->      List[Any]:





    '''simple docstring'''






    return unittest.skipUnless(is_xpu_available()    ,			'test requires a XPU'      )(SCREAMING_SNAKE_CASE__      )
def 						_snake_case(    SCREAMING_SNAKE_CASE__			:	Optional[int]      )							->      Dict:





    '''simple docstring'''






    return unittest.skipUnless(is_mps_available()    ,			'test requires a `mps` backend support in `torch`'      )(SCREAMING_SNAKE_CASE__      )
def 						_snake_case(    SCREAMING_SNAKE_CASE__			:	str      )							->      Optional[int]:





    '''simple docstring'''






    return unittest.skipUnless(
        is_transformers_available() and is_datasets_available()    ,			'test requires the Hugging Face suite'      )(SCREAMING_SNAKE_CASE__      )
def 						_snake_case(    SCREAMING_SNAKE_CASE__			:	List[str]      )							->      Optional[int]:





    '''simple docstring'''






    return unittest.skipUnless(is_bnb_available()    ,			'test requires the bitsandbytes library'      )(SCREAMING_SNAKE_CASE__      )
def 						_snake_case(    SCREAMING_SNAKE_CASE__			:	List[Any]      )							->      Union[str, Any]:





    '''simple docstring'''






    return unittest.skipUnless(is_tpu_available()    ,			'test requires TPU'      )(SCREAMING_SNAKE_CASE__      )
def 						_snake_case(    SCREAMING_SNAKE_CASE__			:	List[str]      )							->      str:





    '''simple docstring'''






    return unittest.skipUnless(torch.cuda.device_count() == 1    ,			'test requires a GPU'      )(SCREAMING_SNAKE_CASE__      )
def 						_snake_case(    SCREAMING_SNAKE_CASE__			:	Any      )							->      List[str]:





    '''simple docstring'''






    return unittest.skipUnless(torch.xpu.device_count() == 1    ,			'test requires a XPU'      )(SCREAMING_SNAKE_CASE__      )
def 						_snake_case(    SCREAMING_SNAKE_CASE__			:	Tuple      )							->      int:





    '''simple docstring'''






    return unittest.skipUnless(torch.cuda.device_count() > 1    ,			'test requires multiple GPUs'      )(SCREAMING_SNAKE_CASE__      )
def 						_snake_case(    SCREAMING_SNAKE_CASE__			:	int      )							->      Union[str, Any]:





    '''simple docstring'''






    return unittest.skipUnless(torch.xpu.device_count() > 1    ,			'test requires multiple XPUs'      )(SCREAMING_SNAKE_CASE__      )
def 						_snake_case(    SCREAMING_SNAKE_CASE__			:	Dict      )							->      Union[str, Any]:





    '''simple docstring'''






    return unittest.skipUnless(is_safetensors_available()    ,			'test requires safetensors'      )(SCREAMING_SNAKE_CASE__      )
def 						_snake_case(    SCREAMING_SNAKE_CASE__			:	str      )							->      Optional[int]:





    '''simple docstring'''






    return unittest.skipUnless(is_deepspeed_available()    ,			'test requires DeepSpeed'      )(SCREAMING_SNAKE_CASE__      )
def 						_snake_case(    SCREAMING_SNAKE_CASE__			:	Optional[int]      )							->      List[str]:





    '''simple docstring'''






    return unittest.skipUnless(is_torch_version('>='    ,			'1.12.0'      )    ,			'test requires torch version >= 1.12.0'      )(SCREAMING_SNAKE_CASE__      )
def 						_snake_case(    SCREAMING_SNAKE_CASE__			:	List[Any]=None    ,			SCREAMING_SNAKE_CASE__			:	Union[str, Any]=None      )							->      List[str]:





    '''simple docstring'''






    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 						_snake_case(    SCREAMING_SNAKE_CASE__			:	Any      )							->      Any:





    '''simple docstring'''






    return unittest.skipUnless(is_tensorboard_available()    ,			'test requires Tensorboard'      )(SCREAMING_SNAKE_CASE__      )
def 						_snake_case(    SCREAMING_SNAKE_CASE__			:	str      )							->      List[Any]:





    '''simple docstring'''






    return unittest.skipUnless(is_wandb_available()    ,			'test requires wandb'      )(SCREAMING_SNAKE_CASE__      )
def 						_snake_case(    SCREAMING_SNAKE_CASE__			:	Optional[int]      )							->      Tuple:





    '''simple docstring'''






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


lowercase_       		=  (
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)
def 						_snake_case(    SCREAMING_SNAKE_CASE__			:	str      )							->      int:





    '''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'    ,			)(SCREAMING_SNAKE_CASE__      )


class  A						(							unittest.TestCase ):







    """simple docstring"""





    lowerCamelCase			=							True


    @classmethod
    def 						snake_case__     (      cls :       List[str]		)->    List[str]:





        '''simple docstring'''







        A__          =   tempfile.mkdtemp()


    @classmethod
    def 						snake_case__     (      cls :       int		)->    str:





        '''simple docstring'''







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


    def 						snake_case__     (      self :       Dict		)->    List[str]:





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




class  A						(							unittest.TestCase ):







    """simple docstring"""





    def 						snake_case__     (      self :       str		)->    Optional[int]:





        '''simple docstring'''







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




class  A						(							unittest.TestCase ):







    """simple docstring"""





    def 						snake_case__     (      self :       Dict,lowercase_ :       Union[mock.Mock, List[mock.Mock]]		)->    str:





        '''simple docstring'''







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




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





    '''simple docstring'''






    A__          =   AcceleratorState()
    A__          =   tensor[None].clone().to(state.device      )
    A__          =   gather(SCREAMING_SNAKE_CASE__      ).cpu()
    A__          =   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 :       Tuple,lowercase_ :       Tuple,lowercase_ :       Dict,lowercase_ :       str		)->    str:





        '''simple docstring'''







        A__          =   returncode
        A__          =   stdout
        A__          =   stderr




async def 						_snake_case(    SCREAMING_SNAKE_CASE__			:	Optional[Any]    ,			SCREAMING_SNAKE_CASE__			:	Dict      )							->      List[str]:





    '''simple docstring'''






    while True:
        A__          =   await stream.readline()
        if line:
            callback(SCREAMING_SNAKE_CASE__      )
        else:
            break
async def 						_snake_case(    SCREAMING_SNAKE_CASE__			:	Dict    ,			SCREAMING_SNAKE_CASE__			:	Optional[int]=None    ,			SCREAMING_SNAKE_CASE__			:	Union[str, Any]=None    ,			SCREAMING_SNAKE_CASE__			:	List[str]=None    ,			SCREAMING_SNAKE_CASE__			:	List[Any]=False    ,			SCREAMING_SNAKE_CASE__			:	List[str]=False      )							->      _RunOutput:





    '''simple docstring'''






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

    A__          =   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)

    A__          =   []
    A__          =   []

    def tee(SCREAMING_SNAKE_CASE__			:	Optional[Any]    ,			SCREAMING_SNAKE_CASE__			:	Any    ,			SCREAMING_SNAKE_CASE__			:	Any    ,			SCREAMING_SNAKE_CASE__			:	Dict=""      ):
        A__          =   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 						_snake_case(    SCREAMING_SNAKE_CASE__			:	Union[str, Any]    ,			SCREAMING_SNAKE_CASE__			:	List[Any]=None    ,			SCREAMING_SNAKE_CASE__			:	int=None    ,			SCREAMING_SNAKE_CASE__			:	List[str]=180    ,			SCREAMING_SNAKE_CASE__			:	Union[str, Any]=False    ,			SCREAMING_SNAKE_CASE__			:	List[Any]=True      )							->      _RunOutput:





    '''simple docstring'''






    A__          =   asyncio.get_event_loop()
    A__          =   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__      )      )

    A__          =   ' '.join(SCREAMING_SNAKE_CASE__      )
    if result.returncode > 0:
        A__          =   '\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						(							_UpperCAmelCase ):







    """simple docstring"""





    pass




def 						_snake_case(    SCREAMING_SNAKE_CASE__			:	List[str]    ,			SCREAMING_SNAKE_CASE__			:	int=False      )							->      List[str]:





    '''simple docstring'''






    try:
        A__          =   subprocess.check_output(SCREAMING_SNAKE_CASE__    ,			stderr=subprocess.STDOUT      )
        if return_stdout:
            if hasattr(SCREAMING_SNAKE_CASE__    ,			'decode'      ):
                A__          =   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




from typing import Dict

from .base import GenericTensor, Pipeline


class  A						(							_UpperCAmelCase ):







    """simple docstring"""





    def 						snake_case__     (      self :       int,lowercase_ :       Dict=None,lowercase_ :       Tuple=None,lowercase_ :       List[Any]=None,**lowercase_ :       Any		)->    Optional[Any]:





        '''simple docstring'''







        if tokenize_kwargs is None:
            A__          =   {}

        if truncation is not None:
            if "truncation" in tokenize_kwargs:
                raise ValueError(
                    'truncation parameter defined twice (given as keyword argument as well as in tokenize_kwargs)'		)
            A__          =   truncation

        A__          =   tokenize_kwargs

        A__          =   {}
        if return_tensors is not None:
            A__          =   return_tensors

        return preprocess_params, {}, postprocess_params


    def 						snake_case__     (      self :       Dict,lowercase_ :       List[Any],**lowercase_ :       Tuple		)->    Dict[str, GenericTensor]:





        '''simple docstring'''







        A__          =   self.framework
        A__          =   self.tokenizer(lowercase_,return_tensors=lowercase_,**lowercase_		)
        return model_inputs


    def 						snake_case__     (      self :       Tuple,lowercase_ :       int		)->    Optional[Any]:





        '''simple docstring'''







        A__          =   self.model(**lowercase_		)
        return model_outputs


    def 						snake_case__     (      self :       Tuple,lowercase_ :       Tuple,lowercase_ :       List[str]=False		)->    Any:





        '''simple docstring'''







        if return_tensors:
            return model_outputs[0]
        if self.framework == "pt":
            return model_outputs[0].tolist()
        elif self.framework == "tf":
            return model_outputs[0].numpy().tolist()


    def __call__(      self :       List[Any],*lowercase_ :       int,**lowercase_ :       Optional[Any]		)->    int:





        '''simple docstring'''







        return super().__call__(*lowercase_,**lowercase_		)

