


'''simple docstring'''
from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_DEFAULT_MEAN,
    IMAGENET_DEFAULT_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    is_batched,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


UpperCamelCase__          = logging.get_logger(__name__)




class      lowerCamelCase_  (      __lowerCAmelCase ):
      lowerCAmelCase__							=	['''pixel_values''']






      def __init__(   self							:       Optional[int]		,		_A							:       int = True		,		_A							:       str = None		,		_A							:       str = PILImageResampling.BICUBIC		,		_A							:       str = True		,		_A							:       List[str] = True		,		_A							:       Tuple = 1 / 255		,		_A							:       str = None		,		_A							:       Optional[int] = True		,		_A							:       Tuple = None		,		_A							:       Tuple = None		,		**_A							:       Dict		,		):


          '''simple docstring'''


          super().__init__(**__SCREAMING_SNAKE_CASE					)
          UpperCAmelCase__     :						str						=							size if size is not None else {'''height''': 224, '''width''': 224}
          UpperCAmelCase__     :						Optional[Any]						=							get_size_dict(__SCREAMING_SNAKE_CASE					)
          UpperCAmelCase__     :						int						=							crop_size if crop_size is not None else {'''height''': 224, '''width''': 224}
          UpperCAmelCase__     :						Optional[Any]						=							get_size_dict(__SCREAMING_SNAKE_CASE		,		default_to_square=__SCREAMING_SNAKE_CASE		,		param_name='''crop_size'''					)

          UpperCAmelCase__     :						Optional[Any]						=							do_resize
          UpperCAmelCase__     :						Union[str, Any]						=							do_rescale
          UpperCAmelCase__     :						List[Any]						=							do_normalize
          UpperCAmelCase__     :						str						=							do_center_crop
          UpperCAmelCase__     :						Dict						=							crop_size
          UpperCAmelCase__     :						Optional[Any]						=							size
          UpperCAmelCase__     :						Tuple						=							resample
          UpperCAmelCase__     :						int						=							rescale_factor
          UpperCAmelCase__     :						str						=							image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
          UpperCAmelCase__     :						List[str]						=							image_std if image_std is not None else IMAGENET_DEFAULT_STD






      def lowercase_				(   self							:       int		,		_A							:       Union[str, Any]		,		_A							:       Any		,		_A							:       List[str] = PILImageResampling.BILINEAR		,		_A							:       str = None		,		**_A							:       List[Any]		,		):


          '''simple docstring'''


          UpperCAmelCase__     :						List[Any]						=							get_size_dict(__SCREAMING_SNAKE_CASE					)

          if "shortest_edge" in size:
              UpperCAmelCase__     :						str						=							get_resize_output_image_size(__SCREAMING_SNAKE_CASE		,		size=size['''shortest_edge''']		,		default_to_square=__SCREAMING_SNAKE_CASE					)
              # size = get_resize_output_image_size(image, size["shortest_edge"], size["longest_edge"])
          elif "height" in size and "width" in size:
              UpperCAmelCase__     :						List[Any]						=							(size['''height'''], size['''width'''])
          else:
              raise ValueError(f"""Size must contain \'height\' and \'width\' keys or \'shortest_edge\' key. Got {size.keys()}"""					)
          return resize(__SCREAMING_SNAKE_CASE		,		size=__SCREAMING_SNAKE_CASE		,		resample=__SCREAMING_SNAKE_CASE		,		data_format=__SCREAMING_SNAKE_CASE		,		**__SCREAMING_SNAKE_CASE					)






      def lowercase_				(   self							:       List[str]		,		_A							:       Optional[Any]		,		_A							:       List[Any]		,		_A							:       List[Any] = None		,		**_A							:       Optional[Any]		,		):


          '''simple docstring'''


          UpperCAmelCase__     :						Optional[Any]						=							get_size_dict(__SCREAMING_SNAKE_CASE					)
          if "height" not in size or "width" not in size:
              raise ValueError(f"""The `size` parameter must contain the keys (height, width). Got {size.keys()}"""					)
          return center_crop(__SCREAMING_SNAKE_CASE		,		size=(size['''height'''], size['''width'''])		,		data_format=__SCREAMING_SNAKE_CASE		,		**__SCREAMING_SNAKE_CASE					)






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


          '''simple docstring'''


          return rescale(__SCREAMING_SNAKE_CASE		,		scale=__SCREAMING_SNAKE_CASE		,		data_format=__SCREAMING_SNAKE_CASE		,		**__SCREAMING_SNAKE_CASE					)






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


          '''simple docstring'''


          return normalize(__SCREAMING_SNAKE_CASE		,		mean=__SCREAMING_SNAKE_CASE		,		std=__SCREAMING_SNAKE_CASE		,		data_format=__SCREAMING_SNAKE_CASE		,		**__SCREAMING_SNAKE_CASE					)






      def lowercase_				(   self							:       int		,		_A							:       Tuple		,		_A							:       List[Any] = None		,		_A							:       Union[str, Any] = None		,		_A							:       int = None		,		_A							:       Tuple = None		,		_A							:       Any = None		,		_A							:       Dict = None		,		_A							:       Tuple = None		,		_A							:       List[Any] = None		,		_A							:       Tuple = None		,		_A							:       str = None		,		_A							:       Optional[int] = None		,		_A							:       Dict = ChannelDimension.FIRST		,		**_A							:       Any		,		):


          '''simple docstring'''


          UpperCAmelCase__     :						List[str]						=							do_resize if do_resize is not None else self.do_resize
          UpperCAmelCase__     :						Optional[Any]						=							do_rescale if do_rescale is not None else self.do_rescale
          UpperCAmelCase__     :						Tuple						=							do_normalize if do_normalize is not None else self.do_normalize
          UpperCAmelCase__     :						Tuple						=							do_center_crop if do_center_crop is not None else self.do_center_crop
          UpperCAmelCase__     :						Optional[Any]						=							crop_size if crop_size is not None else self.crop_size
          UpperCAmelCase__     :						Optional[int]						=							get_size_dict(__SCREAMING_SNAKE_CASE		,		param_name='''crop_size'''		,		default_to_square=__SCREAMING_SNAKE_CASE					)
          UpperCAmelCase__     :						Tuple						=							resample if resample is not None else self.resample
          UpperCAmelCase__     :						Dict						=							rescale_factor if rescale_factor is not None else self.rescale_factor
          UpperCAmelCase__     :						int						=							image_mean if image_mean is not None else self.image_mean
          UpperCAmelCase__     :						str						=							image_std if image_std is not None else self.image_std

          UpperCAmelCase__     :						Optional[Any]						=							size if size is not None else self.size
          UpperCAmelCase__     :						Tuple						=							get_size_dict(__SCREAMING_SNAKE_CASE					)

          if not is_batched(__SCREAMING_SNAKE_CASE					):
              UpperCAmelCase__     :						str						=							[images]

          if not valid_images(__SCREAMING_SNAKE_CASE					):
              raise ValueError(
                  '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
                  '''torch.Tensor, tf.Tensor or jax.ndarray.'''					)

          if do_resize and size is None:
              raise ValueError('''Size must be specified if do_resize is True.'''					)

          if do_center_crop and crop_size is None:
              raise ValueError('''Crop size must be specified if do_center_crop is True.'''					)

          if do_rescale and rescale_factor is None:
              raise ValueError('''Rescale factor must be specified if do_rescale is True.'''					)

          # All transformations expect numpy arrays.
          UpperCAmelCase__     :						Any						=							[to_numpy_array(__SCREAMING_SNAKE_CASE					) for image in images]

          if do_resize:
              UpperCAmelCase__     :						Any						=							[self.resize(image=__SCREAMING_SNAKE_CASE		,		size=__SCREAMING_SNAKE_CASE		,		resample=__SCREAMING_SNAKE_CASE					) for image in images]

          if do_center_crop:
              UpperCAmelCase__     :						Tuple						=							[self.center_crop(image=__SCREAMING_SNAKE_CASE		,		size=__SCREAMING_SNAKE_CASE					) for image in images]

          if do_rescale:
              UpperCAmelCase__     :						int						=							[self.rescale(image=__SCREAMING_SNAKE_CASE		,		scale=__SCREAMING_SNAKE_CASE					) for image in images]

          if do_normalize:
              UpperCAmelCase__     :						int						=							[self.normalize(image=__SCREAMING_SNAKE_CASE		,		mean=__SCREAMING_SNAKE_CASE		,		std=__SCREAMING_SNAKE_CASE					) for image in images]

          UpperCAmelCase__     :						Dict						=							[to_channel_dimension_format(__SCREAMING_SNAKE_CASE		,		__SCREAMING_SNAKE_CASE					) for image in images]

          UpperCAmelCase__     :						Dict						=							{'''pixel_values''': images}
          return BatchFeature(data=__SCREAMING_SNAKE_CASE		,		tensor_type=__SCREAMING_SNAKE_CASE					)






'''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       _UpperCamelCase			(_lowerCamelCase				:  List[Any] ,						_lowerCamelCase				:  Tuple=False						)-> Union[str, Any]:




     '''simple docstring'''





     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(_lowerCamelCase						)
          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_							:	Optional[Any]	     =		parse_flag_from_env('''RUN_SLOW''', default=False)
UpperCAmelCase_							:	Union[str, Any]	     =		parse_flag_from_env('''RUN_REMOTE''', default=False)
UpperCAmelCase_							:	Optional[Any]	     =		parse_flag_from_env('''RUN_LOCAL''', default=True)
UpperCAmelCase_							:	Union[str, Any]	     =		parse_flag_from_env('''RUN_PACKAGED''', default=True)

# Compression
UpperCAmelCase_							:	Dict	     =		pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='''test requires lz4''')
UpperCAmelCase_							:	int	     =		pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='''test requires py7zr''')
UpperCAmelCase_							:	Tuple	     =		pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='''test requires zstandard''')

# Audio
UpperCAmelCase_							:	str	     =		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_							:	Tuple	     =		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_							:	Union[str, Any]	     =		pytest.mark.skipif(
    config.DILL_VERSION <= version.parse('''0.3.2'''),
    reason='''test requires dill>0.3.2 for cloudpickle compatibility''',
)

# Windows
UpperCAmelCase_							:	int	     =		pytest.mark.skipif(
    sys.platform == '''win32''',
    reason='''test should not be run on Windows''',
)







def       _UpperCamelCase			(_lowerCamelCase				:  List[str]						)-> List[Any]:




     '''simple docstring'''





     try:
          import faiss  # noqa
     except ImportError:
          __snake_case            =	unittest.skip('''test requires faiss'''						)(_lowerCamelCase						)
     return test_case







def       _UpperCamelCase			(_lowerCamelCase				:  Union[str, Any]						)-> List[str]:




     '''simple docstring'''





     try:
          import regex  # noqa
     except ImportError:
          __snake_case            =	unittest.skip('''test requires regex'''						)(_lowerCamelCase						)
     return test_case







def       _UpperCamelCase			(_lowerCamelCase				:  Union[str, Any]						)-> Union[str, Any]:




     '''simple docstring'''





     try:
          import elasticsearch  # noqa
     except ImportError:
          __snake_case            =	unittest.skip('''test requires elasticsearch'''						)(_lowerCamelCase						)
     return test_case







def       _UpperCamelCase			(_lowerCamelCase				:  Dict						)-> List[Any]:




     '''simple docstring'''





     try:
          import sqlalchemy  # noqa
     except ImportError:
          __snake_case            =	unittest.skip('''test requires sqlalchemy'''						)(_lowerCamelCase						)
     return test_case







def       _UpperCamelCase			(_lowerCamelCase				:  List[str]						)-> List[str]:




     '''simple docstring'''





     if not config.TORCH_AVAILABLE:
          __snake_case            =	unittest.skip('''test requires PyTorch'''						)(_lowerCamelCase						)
     return test_case







def       _UpperCamelCase			(_lowerCamelCase				:  Optional[Any]						)-> Dict:




     '''simple docstring'''





     if not config.TF_AVAILABLE:
          __snake_case            =	unittest.skip('''test requires TensorFlow'''						)(_lowerCamelCase						)
     return test_case







def       _UpperCamelCase			(_lowerCamelCase				:  int						)-> Any:




     '''simple docstring'''





     if not config.JAX_AVAILABLE:
          __snake_case            =	unittest.skip('''test requires JAX'''						)(_lowerCamelCase						)
     return test_case







def       _UpperCamelCase			(_lowerCamelCase				:  Tuple						)-> str:




     '''simple docstring'''





     if not config.PIL_AVAILABLE:
          __snake_case            =	unittest.skip('''test requires Pillow'''						)(_lowerCamelCase						)
     return test_case







def       _UpperCamelCase			(_lowerCamelCase				:  Dict						)-> Any:




     '''simple docstring'''





     try:
          import transformers  # noqa F401
     except ImportError:
          return unittest.skip('''test requires transformers'''						)(_lowerCamelCase						)
     else:
          return test_case







def       _UpperCamelCase			(_lowerCamelCase				:  int						)-> Tuple:




     '''simple docstring'''





     try:
          import tiktoken  # noqa F401
     except ImportError:
          return unittest.skip('''test requires tiktoken'''						)(_lowerCamelCase						)
     else:
          return test_case







def       _UpperCamelCase			(_lowerCamelCase				:  Dict						)-> str:




     '''simple docstring'''





     try:
          import spacy  # noqa F401
     except ImportError:
          return unittest.skip('''test requires spacy'''						)(_lowerCamelCase						)
     else:
          return test_case







def       _UpperCamelCase			(_lowerCamelCase				:  int						)-> Dict:




     '''simple docstring'''





     def _require_spacy_model(_lowerCamelCase				:  int						):
          try:
               import spacy  # noqa F401

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

     return _require_spacy_model







def       _UpperCamelCase			(_lowerCamelCase				:  str						)-> Dict:




     '''simple docstring'''





     try:
          import pyspark  # noqa F401
     except ImportError:
          return unittest.skip('''test requires pyspark'''						)(_lowerCamelCase						)
     else:
          return test_case







def       _UpperCamelCase			(_lowerCamelCase				:  Tuple						)-> str:




     '''simple docstring'''





     try:
          import joblibspark  # noqa F401
     except ImportError:
          return unittest.skip('''test requires joblibspark'''						)(_lowerCamelCase						)
     else:
          return test_case







def       _UpperCamelCase			(_lowerCamelCase				:  Any						)-> int:




     '''simple docstring'''





     if not _run_slow_tests or _run_slow_tests == 0:
          __snake_case            =	unittest.skip('''test is slow'''						)(_lowerCamelCase						)
     return test_case







def       _UpperCamelCase			(_lowerCamelCase				:  Any						)-> Optional[Any]:




     '''simple docstring'''





     if not _run_local_tests or _run_local_tests == 0:
          __snake_case            =	unittest.skip('''test is local'''						)(_lowerCamelCase						)
     return test_case







def       _UpperCamelCase			(_lowerCamelCase				:  str						)-> int:




     '''simple docstring'''





     if not _run_packaged_tests or _run_packaged_tests == 0:
          __snake_case            =	unittest.skip('''test is packaged'''						)(_lowerCamelCase						)
     return test_case







def       _UpperCamelCase			(_lowerCamelCase				:  Optional[int]						)-> str:




     '''simple docstring'''





     if not _run_remote_tests or _run_remote_tests == 0:
          __snake_case            =	unittest.skip('''test requires remote'''						)(_lowerCamelCase						)
     return test_case







def       _UpperCamelCase			(*_lowerCamelCase				:  str						)-> Optional[int]:




     '''simple docstring'''





     def decorate(cls				:  Optional[Any]						):
          for name, fn in cls.__dict__.items():
               if callable(_lowerCamelCase						) and name.startswith('''test'''						):
                    for decorator in decorators:
                         __snake_case            =	decorator(_lowerCamelCase						)
                    setattr(cls ,						_lowerCamelCase ,						_lowerCamelCase						)
          return cls

     return decorate





class      lowerCAmelCase (			__lowerCAmelCase):
       pass





class      lowerCAmelCase (			__lowerCAmelCase):
       __lowercase	:   List[str]										=      0
       __lowercase	:   Dict										=      1
       __lowercase	:   List[Any]										=      2







@contextmanager
def       _UpperCamelCase			(_lowerCamelCase				:  Dict=OfflineSimulationMode.CONNECTION_FAILS ,						_lowerCamelCase				:  Optional[int]=1E-16						)-> Tuple:




     '''simple docstring'''





     __snake_case            =	requests.Session().request

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

     def raise_connection_error(_lowerCamelCase				:  Union[str, Any] ,						_lowerCamelCase				:  Optional[int] ,						**_lowerCamelCase				:  Dict						):
          raise requests.ConnectionError('''Offline mode is enabled.''' ,						request=_lowerCamelCase						)

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







@contextmanager
def       _UpperCamelCase			(*_lowerCamelCase				:  Union[str, Any] ,						**_lowerCamelCase				:  List[str]						)-> Any:




     '''simple docstring'''





     __snake_case            =	str(Path().resolve()						)
     with tempfile.TemporaryDirectory(*_lowerCamelCase ,						**_lowerCamelCase						) as tmp_dir:
          try:
               os.chdir(_lowerCamelCase						)
               yield
          finally:
               os.chdir(_lowerCamelCase						)







@contextmanager
def       _UpperCamelCase			()-> Optional[int]:




     '''simple docstring'''





     import gc

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







@contextmanager
def       _UpperCamelCase			()-> List[Any]:




     '''simple docstring'''





     import gc

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







def       _UpperCamelCase			(_lowerCamelCase				:  Any ,						_lowerCamelCase				:  int						)-> Any:




     '''simple docstring'''





     return deepcopy(_lowerCamelCase						).integers(0 ,						1_00 ,						10						).tolist() == deepcopy(_lowerCamelCase						).integers(0 ,						1_00 ,						10						).tolist()







def       _UpperCamelCase			(_lowerCamelCase				:  Union[str, Any]						)-> List[Any]:




     '''simple docstring'''





     import decorator
     from requests.exceptions import HTTPError

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

     return decorator.decorator(_wrapper ,						_lowerCamelCase						)





class      lowerCAmelCase :


       def __init__( self     ,	__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE	)   ->	Dict:



            '''simple docstring'''




            __snake_case            =	returncode
            __snake_case            =	stdout
            __snake_case            =	stderr







async def       _UpperCamelCase			(_lowerCamelCase				:  List[str] ,						_lowerCamelCase				:  Union[str, Any]						)-> Dict:




     '''simple docstring'''





     while True:
          __snake_case            =	await stream.readline()
          if line:
               callback(_lowerCamelCase						)
          else:
               break







async def       _UpperCamelCase			(_lowerCamelCase				:  Tuple ,						_lowerCamelCase				:  Optional[int]=None ,						_lowerCamelCase				:  Optional[Any]=None ,						_lowerCamelCase				:  Tuple=None ,						_lowerCamelCase				:  Dict=False ,						_lowerCamelCase				:  List[Any]=False						)-> _RunOutput:




     '''simple docstring'''





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

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

     # 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(_lowerCamelCase				:  int ,						_lowerCamelCase				:  List[Any] ,						_lowerCamelCase				:  str ,						_lowerCamelCase				:  Dict=""						):
          __snake_case            =	line.decode('''utf-8'''						).rstrip()
          sink.append(_lowerCamelCase						)
          if not quiet:
               print(_lowerCamelCase ,						_lowerCamelCase ,						file=_lowerCamelCase						)

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







def       _UpperCamelCase			(_lowerCamelCase				:  Optional[Any] ,						_lowerCamelCase				:  Any=None ,						_lowerCamelCase				:  List[str]=None ,						_lowerCamelCase				:  Optional[Any]=1_80 ,						_lowerCamelCase				:  Dict=False ,						_lowerCamelCase				:  int=True						)-> _RunOutput:




     '''simple docstring'''





     __snake_case            =	asyncio.get_event_loop()
     __snake_case            =	loop.run_until_complete(
         _stream_subprocess(_lowerCamelCase ,						env=_lowerCamelCase ,						stdin=_lowerCamelCase ,						timeout=_lowerCamelCase ,						quiet=_lowerCamelCase ,						echo=_lowerCamelCase						)						)

     __snake_case            =	''' '''.join(_lowerCamelCase						)
     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}'''						)

     # 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       _UpperCamelCase			()-> Dict:




     '''simple docstring'''





     __snake_case            =	os.environ.get('''PYTEST_XDIST_WORKER''' ,						'''gw0'''						)
     __snake_case            =	re.sub(R'''^gw''' ,						'''''' ,						_lowerCamelCase ,						0 ,						re.M						)
     return int(_lowerCamelCase						)







def       _UpperCamelCase			()-> Tuple:




     '''simple docstring'''





     __snake_case            =	2_95_00
     __snake_case            =	pytest_xdist_worker_id()
     return port + uniq_delta






