





import inspect
import unittest

from transformers import YolosConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
  import torch
  from torch import nn

  from transformers import YolosForObjectDetection, YolosModel
  from transformers.models.yolos.modeling_yolos import YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import AutoImageProcessor



class 					__snake_case	:


    '''simple docstring'''







    def __init__(       self   ,				A_   ,				A_=13   ,				A_=[30, 30]   ,				A_=2   ,				A_=3   ,				A_=True   ,				A_=True   ,				A_=32   ,				A_=5   ,				A_=4   ,				A_=37   ,				A_="gelu"   ,				A_=0.1   ,				A_=0.1   ,				A_=10   ,				A_=0.02   ,				A_=3   ,				A_=None   ,				A_=8   ,				A_=10   ,				):





        '''simple docstring'''

        SCREAMING_SNAKE_CASE__											=			parent
        SCREAMING_SNAKE_CASE__											=			batch_size
        SCREAMING_SNAKE_CASE__											=			image_size
        SCREAMING_SNAKE_CASE__											=			patch_size
        SCREAMING_SNAKE_CASE__											=			num_channels
        SCREAMING_SNAKE_CASE__											=			is_training
        SCREAMING_SNAKE_CASE__											=			use_labels
        SCREAMING_SNAKE_CASE__											=			hidden_size
        SCREAMING_SNAKE_CASE__											=			num_hidden_layers
        SCREAMING_SNAKE_CASE__											=			num_attention_heads
        SCREAMING_SNAKE_CASE__											=			intermediate_size
        SCREAMING_SNAKE_CASE__											=			hidden_act
        SCREAMING_SNAKE_CASE__											=			hidden_dropout_prob
        SCREAMING_SNAKE_CASE__											=			attention_probs_dropout_prob
        SCREAMING_SNAKE_CASE__											=			type_sequence_label_size
        SCREAMING_SNAKE_CASE__											=			initializer_range
        SCREAMING_SNAKE_CASE__											=			num_labels
        SCREAMING_SNAKE_CASE__											=			scope
        SCREAMING_SNAKE_CASE__											=			n_targets
        SCREAMING_SNAKE_CASE__											=			num_detection_tokens
        # we set the expected sequence length (which is used in several tests)
        # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) + num_detection_tokens
        SCREAMING_SNAKE_CASE__											=			(image_size[1] // patch_size) * (image_size[0] // patch_size)
        SCREAMING_SNAKE_CASE__											=			num_patches + 1 + self.num_detection_tokens



    def  lowercase_					(       self     ):





        '''simple docstring'''

        SCREAMING_SNAKE_CASE__											=			floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]     )

        SCREAMING_SNAKE_CASE__											=			None
        if self.use_labels:
            # labels is a list of Dict (each Dict being the labels for a given example in the batch)
            SCREAMING_SNAKE_CASE__											=			[]
            for i in range(self.batch_size     ):
                SCREAMING_SNAKE_CASE__											=			{}
                SCREAMING_SNAKE_CASE__											=			torch.randint(
                    high=self.num_labels   ,				size=(self.n_targets,)   ,				device=A_     )
                SCREAMING_SNAKE_CASE__											=			torch.rand(self.n_targets   ,				4   ,				device=A_     )
                labels.append(A_     )

        SCREAMING_SNAKE_CASE__											=			self.get_config()

        return config, pixel_values, labels



    def  lowercase_					(       self     ):





        '''simple docstring'''

        return YolosConfig(
            image_size=self.image_size   ,				patch_size=self.patch_size   ,				num_channels=self.num_channels   ,				hidden_size=self.hidden_size   ,				num_hidden_layers=self.num_hidden_layers   ,				num_attention_heads=self.num_attention_heads   ,				intermediate_size=self.intermediate_size   ,				hidden_act=self.hidden_act   ,				hidden_dropout_prob=self.hidden_dropout_prob   ,				attention_probs_dropout_prob=self.attention_probs_dropout_prob   ,				is_decoder=A_   ,				initializer_range=self.initializer_range   ,				num_detection_tokens=self.num_detection_tokens   ,				num_labels=self.num_labels   ,				)



    def  lowercase_					(       self   ,				A_   ,				A_   ,				A_     ):





        '''simple docstring'''

        SCREAMING_SNAKE_CASE__											=			YolosModel(config=A_     )
        model.to(A_     )
        model.eval()
        SCREAMING_SNAKE_CASE__											=			model(A_     )
        self.parent.assertEqual(
            result.last_hidden_state.shape   ,				(self.batch_size, self.expected_seq_len, self.hidden_size)     )



    def  lowercase_					(       self   ,				A_   ,				A_   ,				A_     ):





        '''simple docstring'''

        SCREAMING_SNAKE_CASE__											=			YolosForObjectDetection(A_     )
        model.to(A_     )
        model.eval()

        SCREAMING_SNAKE_CASE__											=			model(pixel_values=A_     )
        SCREAMING_SNAKE_CASE__											=			model(A_     )

        self.parent.assertEqual(result.logits.shape   ,				(self.batch_size, self.num_detection_tokens, self.num_labels + 1)     )
        self.parent.assertEqual(result.pred_boxes.shape   ,				(self.batch_size, self.num_detection_tokens, 4)     )

        SCREAMING_SNAKE_CASE__											=			model(pixel_values=A_   ,				labels=A_     )

        self.parent.assertEqual(result.loss.shape   ,				()     )
        self.parent.assertEqual(result.logits.shape   ,				(self.batch_size, self.num_detection_tokens, self.num_labels + 1)     )
        self.parent.assertEqual(result.pred_boxes.shape   ,				(self.batch_size, self.num_detection_tokens, 4)     )




    def  lowercase_					(       self     ):





        '''simple docstring'''

        SCREAMING_SNAKE_CASE__											=			self.prepare_config_and_inputs()
        SCREAMING_SNAKE_CASE__				,		SCREAMING_SNAKE_CASE__				,		SCREAMING_SNAKE_CASE__											=			config_and_inputs
        SCREAMING_SNAKE_CASE__											=			{'''pixel_values''': pixel_values}
        return config, inputs_dict





@require_torch
class 					__snake_case	(  __SCREAMING_SNAKE_CASE			,     __SCREAMING_SNAKE_CASE			,     unittest.TestCase    ):


    '''simple docstring'''







    lowerCamelCase__    :		Tuple				=	(YolosModel, YolosForObjectDetection) if is_torch_available() else ()
    lowerCamelCase__    :		int				=	(
        {"""feature-extraction""": YolosModel, """object-detection""": YolosForObjectDetection} if is_torch_available() else {}
    )

    lowerCamelCase__    :		Optional[Any]				=	False
    lowerCamelCase__    :		Union[str, Any]				=	False
    lowerCamelCase__    :		str				=	False
    lowerCamelCase__    :		Optional[Any]				=	False



    def  lowercase_					(       self   ,				A_   ,				A_   ,				A_=False     ):





        '''simple docstring'''

        SCREAMING_SNAKE_CASE__											=			super()._prepare_for_class(A_   ,				A_   ,				return_labels=A_     )

        if return_labels:
            if model_class.__name__ == "YolosForObjectDetection":
                SCREAMING_SNAKE_CASE__											=			[]
                for i in range(self.model_tester.batch_size     ):
                    SCREAMING_SNAKE_CASE__											=			{}
                    SCREAMING_SNAKE_CASE__											=			torch.ones(
                        size=(self.model_tester.n_targets,)   ,				device=A_   ,				dtype=torch.long     )
                    SCREAMING_SNAKE_CASE__											=			torch.ones(
                        self.model_tester.n_targets   ,				4   ,				device=A_   ,				dtype=torch.float     )
                    labels.append(A_     )
                SCREAMING_SNAKE_CASE__											=			labels

        return inputs_dict



    def  lowercase_					(       self     ):





        '''simple docstring'''

        SCREAMING_SNAKE_CASE__											=			YolosModelTester(self     )
        SCREAMING_SNAKE_CASE__											=			ConfigTester(self   ,				config_class=A_   ,				has_text_modality=A_   ,				hidden_size=37     )



    def  lowercase_					(       self     ):





        '''simple docstring'''

        self.config_tester.run_common_tests()



    def  lowercase_					(       self     ):





        '''simple docstring'''

        pass



    def  lowercase_					(       self     ):





        '''simple docstring'''

        SCREAMING_SNAKE_CASE__				,		SCREAMING_SNAKE_CASE__											=			self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
            SCREAMING_SNAKE_CASE__											=			model_class(A_     )
            self.assertIsInstance(model.get_input_embeddings()   ,				(nn.Module)     )
            SCREAMING_SNAKE_CASE__											=			model.get_output_embeddings()
            self.assertTrue(x is None or isinstance(A_   ,				nn.Linear     )     )



    def  lowercase_					(       self     ):





        '''simple docstring'''

        SCREAMING_SNAKE_CASE__				,		SCREAMING_SNAKE_CASE__											=			self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
            SCREAMING_SNAKE_CASE__											=			model_class(A_     )
            SCREAMING_SNAKE_CASE__											=			inspect.signature(model.forward     )
            # signature.parameters is an OrderedDict => so arg_names order is deterministic
            SCREAMING_SNAKE_CASE__											=			[*signature.parameters.keys()]

            SCREAMING_SNAKE_CASE__											=			['''pixel_values''']
            self.assertListEqual(arg_names[:1]   ,				A_     )



    def  lowercase_					(       self     ):





        '''simple docstring'''

        SCREAMING_SNAKE_CASE__											=			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*A_     )



    def  lowercase_					(       self     ):





        '''simple docstring'''

        SCREAMING_SNAKE_CASE__				,		SCREAMING_SNAKE_CASE__											=			self.model_tester.prepare_config_and_inputs_for_common()
        SCREAMING_SNAKE_CASE__											=			True

        # in YOLOS, the seq_len is different
        SCREAMING_SNAKE_CASE__											=			self.model_tester.expected_seq_len
        for model_class in self.all_model_classes:
            SCREAMING_SNAKE_CASE__											=			True
            SCREAMING_SNAKE_CASE__											=			False
            SCREAMING_SNAKE_CASE__											=			True
            SCREAMING_SNAKE_CASE__											=			model_class(A_     )
            model.to(A_     )
            model.eval()
            with torch.no_grad():
                SCREAMING_SNAKE_CASE__											=			model(**self._prepare_for_class(A_   ,				A_     )     )
            SCREAMING_SNAKE_CASE__											=			outputs.attentions
            self.assertEqual(len(A_     )   ,				self.model_tester.num_hidden_layers     )

            # check that output_attentions also work using config
            del inputs_dict["output_attentions"]
            SCREAMING_SNAKE_CASE__											=			True
            SCREAMING_SNAKE_CASE__											=			model_class(A_     )
            model.to(A_     )
            model.eval()
            with torch.no_grad():
                SCREAMING_SNAKE_CASE__											=			model(**self._prepare_for_class(A_   ,				A_     )     )
            SCREAMING_SNAKE_CASE__											=			outputs.attentions
            self.assertEqual(len(A_     )   ,				self.model_tester.num_hidden_layers     )

            self.assertListEqual(
                list(attentions[0].shape[-3:]     )   ,				[self.model_tester.num_attention_heads, seq_len, seq_len]   ,				)
            SCREAMING_SNAKE_CASE__											=			len(A_     )

            # Check attention is always last and order is fine
            SCREAMING_SNAKE_CASE__											=			True
            SCREAMING_SNAKE_CASE__											=			True
            SCREAMING_SNAKE_CASE__											=			model_class(A_     )
            model.to(A_     )
            model.eval()
            with torch.no_grad():
                SCREAMING_SNAKE_CASE__											=			model(**self._prepare_for_class(A_   ,				A_     )     )

            SCREAMING_SNAKE_CASE__											=			1
            self.assertEqual(out_len + added_hidden_states   ,				len(A_     )     )

            SCREAMING_SNAKE_CASE__											=			outputs.attentions

            self.assertEqual(len(A_     )   ,				self.model_tester.num_hidden_layers     )
            self.assertListEqual(
                list(self_attentions[0].shape[-3:]     )   ,				[self.model_tester.num_attention_heads, seq_len, seq_len]   ,				)



    def  lowercase_					(       self     ):





        '''simple docstring'''

        def check_hidden_states_output(A_   ,				A_   ,				A_     ):
            SCREAMING_SNAKE_CASE__											=			model_class(A_     )
            model.to(A_     )
            model.eval()

            with torch.no_grad():
                SCREAMING_SNAKE_CASE__											=			model(**self._prepare_for_class(A_   ,				A_     )     )

            SCREAMING_SNAKE_CASE__											=			outputs.hidden_states

            SCREAMING_SNAKE_CASE__											=			getattr(
                self.model_tester   ,				'''expected_num_hidden_layers'''   ,				self.model_tester.num_hidden_layers + 1     )
            self.assertEqual(len(A_     )   ,				A_     )

            # YOLOS has a different seq_length
            SCREAMING_SNAKE_CASE__											=			self.model_tester.expected_seq_len

            self.assertListEqual(
                list(hidden_states[0].shape[-2:]     )   ,				[seq_length, self.model_tester.hidden_size]   ,				)

        SCREAMING_SNAKE_CASE__				,		SCREAMING_SNAKE_CASE__											=			self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
            SCREAMING_SNAKE_CASE__											=			True
            check_hidden_states_output(A_   ,				A_   ,				A_     )

            # check that output_hidden_states also work using config
            del inputs_dict["output_hidden_states"]
            SCREAMING_SNAKE_CASE__											=			True

            check_hidden_states_output(A_   ,				A_   ,				A_     )



    def  lowercase_					(       self     ):





        '''simple docstring'''

        SCREAMING_SNAKE_CASE__											=			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_object_detection(*A_     )




    @slow
    def  lowercase_					(       self     ):





        '''simple docstring'''

        for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            SCREAMING_SNAKE_CASE__											=			YolosModel.from_pretrained(A_     )
            self.assertIsNotNone(A_     )





def 							__snake_case							(    )				->						Any:
    SCREAMING_SNAKE_CASE__											=			Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''	)
    return image



@require_torch
@require_vision
class 					__snake_case	(  unittest.TestCase    ):


    '''simple docstring'''







    @cached_property
    def  lowercase_					(       self     ):





        '''simple docstring'''

        return AutoImageProcessor.from_pretrained('''hustvl/yolos-small'''     ) if is_vision_available() else None




    @slow
    def  lowercase_					(       self     ):





        '''simple docstring'''

        SCREAMING_SNAKE_CASE__											=			YolosForObjectDetection.from_pretrained('''hustvl/yolos-small'''     ).to(A_     )

        SCREAMING_SNAKE_CASE__											=			self.default_image_processor
        SCREAMING_SNAKE_CASE__											=			prepare_img()
        SCREAMING_SNAKE_CASE__											=			image_processor(images=A_   ,				return_tensors='''pt'''     ).to(A_     )

        # forward pass
        with torch.no_grad():
            SCREAMING_SNAKE_CASE__											=			model(inputs.pixel_values     )

        # verify outputs
        SCREAMING_SNAKE_CASE__											=			torch.Size((1, 1_00, 92)     )
        self.assertEqual(outputs.logits.shape   ,				A_     )

        SCREAMING_SNAKE_CASE__											=			torch.tensor(
            [[-24.0248, -10.3024, -14.8290], [-42.0392, -16.8200, -27.4334], [-27.2743, -11.8154, -18.7148]]   ,				device=A_   ,				)
        SCREAMING_SNAKE_CASE__											=			torch.tensor(
            [[0.2559, 0.5455, 0.4706], [0.2989, 0.7279, 0.1875], [0.7732, 0.4017, 0.4462]]   ,				device=A_     )
        self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]   ,				A_   ,				atol=1E-4     )     )
        self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3]   ,				A_   ,				atol=1E-4     )     )

        # verify postprocessing
        SCREAMING_SNAKE_CASE__											=			image_processor.post_process_object_detection(
            A_   ,				threshold=0.3   ,				target_sizes=[image.size[::-1]]     )[0]
        SCREAMING_SNAKE_CASE__											=			torch.tensor([0.9994, 0.9790, 0.9964, 0.9972, 0.9861]     ).to(A_     )
        SCREAMING_SNAKE_CASE__											=			[75, 75, 17, 63, 17]
        SCREAMING_SNAKE_CASE__											=			torch.tensor([335.0609, 79.3848, 375.4216, 187.2495]     ).to(A_     )

        self.assertEqual(len(results['''scores''']     )   ,				5     )
        self.assertTrue(torch.allclose(results['''scores''']   ,				A_   ,				atol=1E-4     )     )
        self.assertSequenceEqual(results['''labels'''].tolist()   ,				A_     )
        self.assertTrue(torch.allclose(results['''boxes'''][0, :]   ,				A_     )     )

'''simple docstring'''




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 __lowerCAmelCase					(				UpperCamelCase__							,    UpperCamelCase__=False							)      ->       Optional[int]:
    try:
        __lowerCamelCase            =    os.environ[key]
    except KeyError:
        # KEY isn't set, default to `default`.
        __lowerCamelCase            =    default
    else:
        # KEY is set, convert it to True or False.
        try:
            __lowerCamelCase            =    strtobool(UpperCamelCase__							)
        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					=parse_flag_from_env("RUN_SLOW", default=False)
__UpperCAmelCase					=parse_flag_from_env("RUN_REMOTE", default=False)
__UpperCAmelCase					=parse_flag_from_env("RUN_LOCAL", default=True)
__UpperCAmelCase					=parse_flag_from_env("RUN_PACKAGED", default=True)

# Compression
__UpperCAmelCase					=pytest.mark.skipif(not config.LZ4_AVAILABLE, reason="test requires lz4")
__UpperCAmelCase					=pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason="test requires py7zr")
__UpperCAmelCase					=pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason="test requires zstandard")

# Audio
__UpperCAmelCase					=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					=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					=pytest.mark.skipif(
    config.DILL_VERSION <= version.parse("0.3.2"),
    reason="test requires dill>0.3.2 for cloudpickle compatibility",
)

# Windows
__UpperCAmelCase					=pytest.mark.skipif(
    sys.platform == "win32",
    reason="test should not be run on Windows",
)






def __lowerCAmelCase					(				UpperCamelCase__							)      ->       Optional[int]:
    try:
        import faiss  # noqa
    except ImportError:
        __lowerCamelCase            =    unittest.skip('''test requires faiss'''							)(UpperCamelCase__							)
    return test_case






def __lowerCAmelCase					(				UpperCamelCase__							)      ->       Optional[int]:
    try:
        import regex  # noqa
    except ImportError:
        __lowerCamelCase            =    unittest.skip('''test requires regex'''							)(UpperCamelCase__							)
    return test_case






def __lowerCAmelCase					(				UpperCamelCase__							)      ->       Optional[int]:
    try:
        import elasticsearch  # noqa
    except ImportError:
        __lowerCamelCase            =    unittest.skip('''test requires elasticsearch'''							)(UpperCamelCase__							)
    return test_case






def __lowerCAmelCase					(				UpperCamelCase__							)      ->       List[Any]:
    try:
        import sqlalchemy  # noqa
    except ImportError:
        __lowerCamelCase            =    unittest.skip('''test requires sqlalchemy'''							)(UpperCamelCase__							)
    return test_case






def __lowerCAmelCase					(				UpperCamelCase__							)      ->       List[str]:
    if not config.TORCH_AVAILABLE:
        __lowerCamelCase            =    unittest.skip('''test requires PyTorch'''							)(UpperCamelCase__							)
    return test_case






def __lowerCAmelCase					(				UpperCamelCase__							)      ->       Union[str, Any]:
    if not config.TF_AVAILABLE:
        __lowerCamelCase            =    unittest.skip('''test requires TensorFlow'''							)(UpperCamelCase__							)
    return test_case






def __lowerCAmelCase					(				UpperCamelCase__							)      ->       int:
    if not config.JAX_AVAILABLE:
        __lowerCamelCase            =    unittest.skip('''test requires JAX'''							)(UpperCamelCase__							)
    return test_case






def __lowerCAmelCase					(				UpperCamelCase__							)      ->       Tuple:
    if not config.PIL_AVAILABLE:
        __lowerCamelCase            =    unittest.skip('''test requires Pillow'''							)(UpperCamelCase__							)
    return test_case






def __lowerCAmelCase					(				UpperCamelCase__							)      ->       Union[str, Any]:
    try:
        import transformers  # noqa F401
    except ImportError:
        return unittest.skip('''test requires transformers'''							)(UpperCamelCase__							)
    else:
        return test_case






def __lowerCAmelCase					(				UpperCamelCase__							)      ->       str:
    try:
        import tiktoken  # noqa F401
    except ImportError:
        return unittest.skip('''test requires tiktoken'''							)(UpperCamelCase__							)
    else:
        return test_case






def __lowerCAmelCase					(				UpperCamelCase__							)      ->       Tuple:
    try:
        import spacy  # noqa F401
    except ImportError:
        return unittest.skip('''test requires spacy'''							)(UpperCamelCase__							)
    else:
        return test_case






def __lowerCAmelCase					(				UpperCamelCase__							)      ->       Dict:

    def _require_spacy_model(UpperCamelCase__							):
        try:
            import spacy  # noqa F401

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

    return _require_spacy_model






def __lowerCAmelCase					(				UpperCamelCase__							)      ->       List[Any]:
    try:
        import pyspark  # noqa F401
    except ImportError:
        return unittest.skip('''test requires pyspark'''							)(UpperCamelCase__							)
    else:
        return test_case






def __lowerCAmelCase					(				UpperCamelCase__							)      ->       Tuple:
    try:
        import joblibspark  # noqa F401
    except ImportError:
        return unittest.skip('''test requires joblibspark'''							)(UpperCamelCase__							)
    else:
        return test_case






def __lowerCAmelCase					(				UpperCamelCase__							)      ->       Union[str, Any]:
    if not _run_slow_tests or _run_slow_tests == 0:
        __lowerCamelCase            =    unittest.skip('''test is slow'''							)(UpperCamelCase__							)
    return test_case






def __lowerCAmelCase					(				UpperCamelCase__							)      ->       List[str]:
    if not _run_local_tests or _run_local_tests == 0:
        __lowerCamelCase            =    unittest.skip('''test is local'''							)(UpperCamelCase__							)
    return test_case






def __lowerCAmelCase					(				UpperCamelCase__							)      ->       List[str]:
    if not _run_packaged_tests or _run_packaged_tests == 0:
        __lowerCamelCase            =    unittest.skip('''test is packaged'''							)(UpperCamelCase__							)
    return test_case






def __lowerCAmelCase					(				UpperCamelCase__							)      ->       Tuple:
    if not _run_remote_tests or _run_remote_tests == 0:
        __lowerCamelCase            =    unittest.skip('''test requires remote'''							)(UpperCamelCase__							)
    return test_case






def __lowerCAmelCase					(				*UpperCamelCase__							)      ->       List[Any]:
    def decorate(cls							):
        for name, fn in cls.__dict__.items():
            if callable(UpperCamelCase__							) and name.startswith('''test'''							):
                for decorator in decorators:
                    __lowerCamelCase            =    decorator(UpperCamelCase__							)
                setattr(cls							,    UpperCamelCase__							,    UpperCamelCase__							)
        return cls

    return decorate




class        a__ (  UpperCAmelCase__					):
     pass




class        a__ (  UpperCAmelCase__					):
     lowerCamelCase    :	int				=0
     lowerCamelCase    :	List[str]				=1
     lowerCamelCase    :	Union[str, Any]				=2






@contextmanager
def __lowerCAmelCase					(				UpperCamelCase__=OfflineSimulationMode.CONNECTION_FAILS							,    UpperCamelCase__=1E-16							)      ->       str:
    __lowerCamelCase            =    requests.Session().request

    def timeout_request(UpperCamelCase__							,    UpperCamelCase__							,    UpperCamelCase__							,    **UpperCamelCase__							):
        # Change the url to an invalid url so that the connection hangs
        __lowerCamelCase            =    '''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."""							)
        __lowerCamelCase            =    timeout
        try:
            return online_request(UpperCamelCase__							,    UpperCamelCase__							,    **UpperCamelCase__							)
        except Exception as e:
            # The following changes in the error are just here to make the offline timeout error prettier
            __lowerCamelCase            =    url
            __lowerCamelCase            =    e.args[0]
            __lowerCamelCase            =    (max_retry_error.args[0].replace('''10.255.255.1'''							,    f"""OfflineMock[{url}]"""							),)
            __lowerCamelCase            =    (max_retry_error,)
            raise

    def raise_connection_error(UpperCamelCase__							,    UpperCamelCase__							,    **UpperCamelCase__							):
        raise requests.ConnectionError('''Offline mode is enabled.'''							,    request=UpperCamelCase__							)

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






@contextmanager
def __lowerCAmelCase					(				*UpperCamelCase__							,    **UpperCamelCase__							)      ->       Any:
    __lowerCamelCase            =    str(Path().resolve()							)
    with tempfile.TemporaryDirectory(*UpperCamelCase__							,    **UpperCamelCase__							) as tmp_dir:
        try:
            os.chdir(UpperCamelCase__							)
            yield
        finally:
            os.chdir(UpperCamelCase__							)






@contextmanager
def __lowerCAmelCase					(				)      ->       List[Any]:
    import gc

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






@contextmanager
def __lowerCAmelCase					(				)      ->       Any:
    import gc

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






def __lowerCAmelCase					(				UpperCamelCase__							,    UpperCamelCase__							)      ->       Dict:
    return deepcopy(UpperCamelCase__							).integers(0							,    1_00							,    10							).tolist() == deepcopy(UpperCamelCase__							).integers(0							,    1_00							,    10							).tolist()






def __lowerCAmelCase					(				UpperCamelCase__							)      ->       Union[str, Any]:
    import decorator
    from requests.exceptions import HTTPError

    def _wrapper(UpperCamelCase__							,    *UpperCamelCase__							,    **UpperCamelCase__							):
        try:
            return func(*UpperCamelCase__							,    **UpperCamelCase__							)
        except HTTPError as err:
            if str(UpperCamelCase__							).startswith('''500'''							) or str(UpperCamelCase__							).startswith('''502'''							):
                pytest.xfail(str(UpperCamelCase__							)							)
            raise err

    return decorator.decorator(_wrapper							,    UpperCamelCase__							)




class        a__ :






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





         """simple docstring"""



         __lowerCamelCase            =    returncode
         __lowerCamelCase            =    stdout
         __lowerCamelCase            =    stderr






async def __lowerCAmelCase					(				UpperCamelCase__							,    UpperCamelCase__							)      ->       Tuple:
    while True:
        __lowerCamelCase            =    await stream.readline()
        if line:
            callback(UpperCamelCase__							)
        else:
            break






async def __lowerCAmelCase					(				UpperCamelCase__							,    UpperCamelCase__=None							,    UpperCamelCase__=None							,    UpperCamelCase__=None							,    UpperCamelCase__=False							,    UpperCamelCase__=False							)      ->       _RunOutput:
    if echo:
        print('''\nRunning: '''							,    ''' '''.join(UpperCamelCase__							)							)

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

    # 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            =    []
    __lowerCamelCase            =    []

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

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






def __lowerCAmelCase					(				UpperCamelCase__							,    UpperCamelCase__=None							,    UpperCamelCase__=None							,    UpperCamelCase__=1_80							,    UpperCamelCase__=False							,    UpperCamelCase__=True							)      ->       _RunOutput:
    __lowerCamelCase            =    asyncio.get_event_loop()
    __lowerCamelCase            =    loop.run_until_complete(
        _stream_subprocess(UpperCamelCase__							,    env=UpperCamelCase__							,    stdin=UpperCamelCase__							,    timeout=UpperCamelCase__							,    quiet=UpperCamelCase__							,    echo=UpperCamelCase__							)							)

    __lowerCamelCase            =    ''' '''.join(UpperCamelCase__							)
    if result.returncode > 0:
        __lowerCamelCase            =    '''\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 __lowerCAmelCase					(				)      ->       List[str]:
    __lowerCamelCase            =    os.environ.get('''PYTEST_XDIST_WORKER'''							,    '''gw0'''							)
    __lowerCamelCase            =    re.sub(r'''^gw'''							,    ''''''							,    UpperCamelCase__							,    0							,    re.M							)
    return int(UpperCamelCase__							)






def __lowerCAmelCase					(				)      ->       Union[str, Any]:
    __lowerCamelCase            =    2_95_00
    __lowerCamelCase            =    pytest_xdist_worker_id()
    return port + uniq_delta
