


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_		(		_A			:    Dict    ,					_A			:    str=False						):

      """simple docstring"""




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


A      :    List[str]		=					parse_flag_from_env("RUN_SLOW", default=False)

def       lowercase_		(		_A			:    Any						):

      """simple docstring"""




      return unittest.skip("Test was skipped"						)(_A						)

def       lowercase_		(		_A			:    Dict						):

      """simple docstring"""




      return unittest.skipUnless(_run_slow_tests    ,					"test is slow"						)(_A						)

def       lowercase_		(		_A			:    Tuple						):

      """simple docstring"""




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

def       lowercase_		(		_A			:    List[str]						):

      """simple docstring"""




      return unittest.skipUnless(torch.cuda.is_available()    ,					"test requires a GPU"						)(_A						)

def       lowercase_		(		_A			:    Tuple						):

      """simple docstring"""




      return unittest.skipUnless(is_xpu_available()    ,					"test requires a XPU"						)(_A						)

def       lowercase_		(		_A			:    Tuple						):

      """simple docstring"""




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

def       lowercase_		(		_A			:    List[Any]						):

      """simple docstring"""




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

def       lowercase_		(		_A			:    Tuple						):

      """simple docstring"""




      return unittest.skipUnless(is_bnb_available()    ,					"test requires the bitsandbytes library"						)(_A						)

def       lowercase_		(		_A			:    Union[str, Any]						):

      """simple docstring"""




      return unittest.skipUnless(is_tpu_available()    ,					"test requires TPU"						)(_A						)

def       lowercase_		(		_A			:    Tuple						):

      """simple docstring"""




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

def       lowercase_		(		_A			:    Optional[int]						):

      """simple docstring"""




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

def       lowercase_		(		_A			:    Dict						):

      """simple docstring"""




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

def       lowercase_		(		_A			:    List[str]						):

      """simple docstring"""




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

def       lowercase_		(		_A			:    Union[str, Any]						):

      """simple docstring"""




      return unittest.skipUnless(is_safetensors_available()    ,					"test requires safetensors"						)(_A						)

def       lowercase_		(		_A			:    List[str]						):

      """simple docstring"""




      return unittest.skipUnless(is_deepspeed_available()    ,					"test requires DeepSpeed"						)(_A						)

def       lowercase_		(		_A			:    Union[str, Any]						):

      """simple docstring"""




      return unittest.skipUnless(is_torch_version(">="    ,					"1.12.0"						)    ,					"test requires torch version >= 1.12.0"						)(_A						)

def       lowercase_		(		_A			:    Union[str, Any]=None    ,					_A			:    List[Any]=None						):

      """simple docstring"""




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

def       lowercase_		(		_A			:    Dict						):

      """simple docstring"""




      return unittest.skipUnless(is_tensorboard_available()    ,					"test requires Tensorboard"						)(_A						)

def       lowercase_		(		_A			:    Dict						):

      """simple docstring"""




      return unittest.skipUnless(is_wandb_available()    ,					"test requires wandb"						)(_A						)

def       lowercase_		(		_A			:    Dict						):

      """simple docstring"""




      return unittest.skipUnless(is_comet_ml_available()    ,					"test requires comet_ml"						)(_A						)


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

def       lowercase_		(		_A			:    Optional[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"    ,					)(_A						)







class 			_lowercase (							unittest.TestCase):


       """simple docstring"""




       A__											=			True





       @classmethod
       def 						lowerCAmelCase     (   cls							:			List[Any]       ):


             '''simple docstring'''



             lowerCamelCase__		:				Any    =  tempfile.mkdtemp()





       @classmethod
       def 						lowerCAmelCase     (   cls							:			List[str]       ):


             '''simple docstring'''



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





       def 						lowerCAmelCase     (   self							:			int       ):


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







class 			_lowercase (							unittest.TestCase):


       """simple docstring"""




       def 						lowerCAmelCase     (   self							:			Optional[Any]       ):


             '''simple docstring'''



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







class 			_lowercase (							unittest.TestCase):


       """simple docstring"""




       def 						lowerCAmelCase     (   self							:			int					,      __lowerCamelCase							:			Union[mock.Mock, List[mock.Mock]]       ):


             '''simple docstring'''



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



def       lowercase_		(		_A			:    Dict						):

      """simple docstring"""




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







class 			_lowercase :


       """simple docstring"""




       def __init__(   self							:			List[Any]					,      __lowerCamelCase							:			Optional[Any]					,      __lowerCamelCase							:			Dict					,      __lowerCamelCase							:			int       ):


             '''simple docstring'''



             lowerCamelCase__		:				str    =  returncode
             lowerCamelCase__		:				int    =  stdout
             lowerCamelCase__		:				Optional[Any]    =  stderr



async def       lowercase_		(		_A			:    List[Any]    ,					_A			:    Any						):

      """simple docstring"""




      while True:
            lowerCamelCase__		:				Optional[Any]    =  await stream.readline()
            if line:
                  callback(_A						)
            else:
                  break

async def       lowercase_		(		_A			:    Any    ,					_A			:    List[Any]=None    ,					_A			:    str=None    ,					_A			:    List[Any]=None    ,					_A			:    List[str]=False    ,					_A			:    Optional[int]=False						):

      """simple docstring"""




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

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

      # 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__		:				Any    =  []
      lowerCamelCase__		:				List[str]    =  []

      def tee(_A			:    Tuple    ,					_A			:    int    ,					_A			:    Dict    ,					_A			:    Optional[Any]=""						):
            lowerCamelCase__		:				Tuple    =  line.decode("utf-8"						).rstrip()
            sink.append(_A						)
            if not quiet:
                  print(_A    ,					_A    ,					file=_A						)

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

def       lowercase_		(		_A			:    List[str]    ,					_A			:    Dict=None    ,					_A			:    str=None    ,					_A			:    Any=180    ,					_A			:    Dict=False    ,					_A			:    Optional[Any]=True						):

      """simple docstring"""




      lowerCamelCase__		:				List[Any]    =  asyncio.get_event_loop()
      lowerCamelCase__		:				Tuple    =  loop.run_until_complete(
          _stream_subprocess(_A    ,					env=_A    ,					stdin=_A    ,					timeout=_A    ,					quiet=_A    ,					echo=_A						)						)

      lowerCamelCase__		:				Any    =  " ".join(_A						)
      if result.returncode > 0:
            lowerCamelCase__		:				Any    =  "\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__):


       """simple docstring"""




       pass



def       lowercase_		(		_A			:    List[str]    ,					_A			:    Dict=False						):

      """simple docstring"""




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






import unittest

from transformers import (
    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TextClassificationPipeline,
    pipeline,
)
from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow

from .test_pipelines_common import ANY


# These 2 model types require different inputs than those of the usual text models.
A      :    Union[str, Any]		=					{"LayoutLMv2Config", "LayoutLMv3Config"}







@is_pipeline_test
class 			_lowercase (							unittest.TestCase):


       """simple docstring"""




       A__											=			MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
       A__											=			TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

       if model_mapping is not None:
              A__											=			{config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP}
       if tf_model_mapping is not None:
              A__											=			{
                  config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
              }





       @require_torch
       def 						lowerCAmelCase     (   self							:			List[str]       ):


             '''simple docstring'''



             lowerCamelCase__		:				Tuple    =  pipeline(
                 task="text-classification"					,      model="hf-internal-testing/tiny-random-distilbert"					,      framework="pt"       )

             lowerCamelCase__		:				Dict    =  text_classifier("This is great !"       )
             self.assertEqual(nested_simplify(__lowerCamelCase       )					,      [{"label": "LABEL_0", "score": 0.5_0_4}]       )

             lowerCamelCase__		:				List[str]    =  text_classifier("This is great !"					,      top_k=2       )
             self.assertEqual(
                 nested_simplify(__lowerCamelCase       )					,      [{"label": "LABEL_0", "score": 0.5_0_4}, {"label": "LABEL_1", "score": 0.4_9_6}]       )

             lowerCamelCase__		:				Optional[int]    =  text_classifier(["This is great !", "This is bad"]					,      top_k=2       )
             self.assertEqual(
                 nested_simplify(__lowerCamelCase       )					,      [
                     [{"label": "LABEL_0", "score": 0.5_0_4}, {"label": "LABEL_1", "score": 0.4_9_6}],
                     [{"label": "LABEL_0", "score": 0.5_0_4}, {"label": "LABEL_1", "score": 0.4_9_6}],
                 ]					,      )

             lowerCamelCase__		:				Any    =  text_classifier("This is great !"					,      top_k=1       )
             self.assertEqual(nested_simplify(__lowerCamelCase       )					,      [{"label": "LABEL_0", "score": 0.5_0_4}]       )

             # Legacy behavior
             lowerCamelCase__		:				Dict    =  text_classifier("This is great !"					,      return_all_scores=__lowerCamelCase       )
             self.assertEqual(nested_simplify(__lowerCamelCase       )					,      [{"label": "LABEL_0", "score": 0.5_0_4}]       )

             lowerCamelCase__		:				str    =  text_classifier("This is great !"					,      return_all_scores=__lowerCamelCase       )
             self.assertEqual(
                 nested_simplify(__lowerCamelCase       )					,      [[{"label": "LABEL_0", "score": 0.5_0_4}, {"label": "LABEL_1", "score": 0.4_9_6}]]       )

             lowerCamelCase__		:				Optional[Any]    =  text_classifier(["This is great !", "Something else"]					,      return_all_scores=__lowerCamelCase       )
             self.assertEqual(
                 nested_simplify(__lowerCamelCase       )					,      [
                     [{"label": "LABEL_0", "score": 0.5_0_4}, {"label": "LABEL_1", "score": 0.4_9_6}],
                     [{"label": "LABEL_0", "score": 0.5_0_4}, {"label": "LABEL_1", "score": 0.4_9_6}],
                 ]					,      )

             lowerCamelCase__		:				Any    =  text_classifier(["This is great !", "Something else"]					,      return_all_scores=__lowerCamelCase       )
             self.assertEqual(
                 nested_simplify(__lowerCamelCase       )					,      [
                     {"label": "LABEL_0", "score": 0.5_0_4},
                     {"label": "LABEL_0", "score": 0.5_0_4},
                 ]					,      )





       @require_torch
       def 						lowerCAmelCase     (   self							:			str       ):


             '''simple docstring'''



             import torch

             lowerCamelCase__		:				int    =  pipeline(
                 task="text-classification"					,      model="hf-internal-testing/tiny-random-distilbert"					,      framework="pt"					,      device=torch.device("cpu"       )					,      )

             lowerCamelCase__		:				Any    =  text_classifier("This is great !"       )
             self.assertEqual(nested_simplify(__lowerCamelCase       )					,      [{"label": "LABEL_0", "score": 0.5_0_4}]       )





       @require_tf
       def 						lowerCAmelCase     (   self							:			int       ):


             '''simple docstring'''



             lowerCamelCase__		:				List[str]    =  pipeline(
                 task="text-classification"					,      model="hf-internal-testing/tiny-random-distilbert"					,      framework="tf"       )

             lowerCamelCase__		:				List[str]    =  text_classifier("This is great !"       )
             self.assertEqual(nested_simplify(__lowerCamelCase       )					,      [{"label": "LABEL_0", "score": 0.5_0_4}]       )





       @slow
       @require_torch
       def 						lowerCAmelCase     (   self							:			List[Any]       ):


             '''simple docstring'''



             lowerCamelCase__		:				Optional[Any]    =  pipeline("text-classification"       )

             lowerCamelCase__		:				List[str]    =  text_classifier("This is great !"       )
             self.assertEqual(nested_simplify(__lowerCamelCase       )					,      [{"label": "POSITIVE", "score": 1.0}]       )
             lowerCamelCase__		:				Optional[int]    =  text_classifier("This is bad !"       )
             self.assertEqual(nested_simplify(__lowerCamelCase       )					,      [{"label": "NEGATIVE", "score": 1.0}]       )
             lowerCamelCase__		:				Tuple    =  text_classifier("Birds are a type of animal"       )
             self.assertEqual(nested_simplify(__lowerCamelCase       )					,      [{"label": "POSITIVE", "score": 0.9_8_8}]       )





       @slow
       @require_tf
       def 						lowerCAmelCase     (   self							:			List[Any]       ):


             '''simple docstring'''



             lowerCamelCase__		:				str    =  pipeline("text-classification"					,      framework="tf"       )

             lowerCamelCase__		:				Optional[int]    =  text_classifier("This is great !"       )
             self.assertEqual(nested_simplify(__lowerCamelCase       )					,      [{"label": "POSITIVE", "score": 1.0}]       )
             lowerCamelCase__		:				Optional[Any]    =  text_classifier("This is bad !"       )
             self.assertEqual(nested_simplify(__lowerCamelCase       )					,      [{"label": "NEGATIVE", "score": 1.0}]       )
             lowerCamelCase__		:				Dict    =  text_classifier("Birds are a type of animal"       )
             self.assertEqual(nested_simplify(__lowerCamelCase       )					,      [{"label": "POSITIVE", "score": 0.9_8_8}]       )





       def 						lowerCAmelCase     (   self							:			Tuple					,      __lowerCamelCase							:			Any					,      __lowerCamelCase							:			str					,      __lowerCamelCase							:			Optional[Any]       ):


             '''simple docstring'''



             lowerCamelCase__		:				Tuple    =  TextClassificationPipeline(model=__lowerCamelCase					,      tokenizer=__lowerCamelCase       )
             return text_classifier, ["HuggingFace is in", "This is another test"]





       def 						lowerCAmelCase     (   self							:			Optional[Any]					,      __lowerCamelCase							:			Tuple					,      __lowerCamelCase							:			Any       ):


             '''simple docstring'''



             lowerCamelCase__		:				int    =  text_classifier.model
             # Small inputs because BartTokenizer tiny has maximum position embeddings = 22
             lowerCamelCase__		:				List[Any]    =  "HuggingFace is in"
             lowerCamelCase__		:				Tuple    =  text_classifier(__lowerCamelCase       )

             self.assertEqual(nested_simplify(__lowerCamelCase       )					,      [{"label": ANY(__lowerCamelCase       ), "score": ANY(__lowerCamelCase       )}]       )
             self.assertTrue(outputs[0]["label"] in model.config.idalabel.values()       )

             lowerCamelCase__		:				Optional[int]    =  ["HuggingFace is in ", "Paris is in France"]
             lowerCamelCase__		:				Dict    =  text_classifier(__lowerCamelCase       )
             self.assertEqual(
                 nested_simplify(__lowerCamelCase       )					,      [{"label": ANY(__lowerCamelCase       ), "score": ANY(__lowerCamelCase       )}, {"label": ANY(__lowerCamelCase       ), "score": ANY(__lowerCamelCase       )}]					,      )
             self.assertTrue(outputs[0]["label"] in model.config.idalabel.values()       )
             self.assertTrue(outputs[1]["label"] in model.config.idalabel.values()       )

             # Forcing to get all results with `top_k=None`
             # This is NOT the legacy format
             lowerCamelCase__		:				List[Any]    =  text_classifier(__lowerCamelCase					,      top_k=__lowerCamelCase       )
             lowerCamelCase__		:				Union[str, Any]    =  len(model.config.idalabel.values()       )
             self.assertEqual(
                 nested_simplify(__lowerCamelCase       )					,      [[{"label": ANY(__lowerCamelCase       ), "score": ANY(__lowerCamelCase       )}] * N, [{"label": ANY(__lowerCamelCase       ), "score": ANY(__lowerCamelCase       )}] * N]					,      )

             lowerCamelCase__		:				Optional[int]    =  {"text": "HuggingFace is in ", "text_pair": "Paris is in France"}
             lowerCamelCase__		:				List[Any]    =  text_classifier(__lowerCamelCase       )
             self.assertEqual(
                 nested_simplify(__lowerCamelCase       )					,      {"label": ANY(__lowerCamelCase       ), "score": ANY(__lowerCamelCase       )}					,      )
             self.assertTrue(outputs["label"] in model.config.idalabel.values()       )

             # This might be used a text pair, but tokenizer + pipe interaction
             # makes it hard to understand that it's not using the pair properly
             # https://github.com/huggingface/transformers/issues/17305
             # We disabled this usage instead as it was outputting wrong outputs.
             lowerCamelCase__		:				Any    =  [["HuggingFace is in ", "Paris is in France"]]
             with self.assertRaises(__lowerCamelCase       ):
                   text_classifier(__lowerCamelCase       )

             # This used to be valid for doing text pairs
             # We're keeping it working because of backward compatibility
             lowerCamelCase__		:				int    =  text_classifier([[["HuggingFace is in ", "Paris is in France"]]]       )
             self.assertEqual(
                 nested_simplify(__lowerCamelCase       )					,      [{"label": ANY(__lowerCamelCase       ), "score": ANY(__lowerCamelCase       )}]					,      )
             self.assertTrue(outputs[0]["label"] in model.config.idalabel.values()       )


