



import argparse
import dataclasses
import json
import logging
import os
import shutil
from typing import List, Optional

import datasets
from accelerate import Accelerator
from datasets import load_dataset
from finetuning import finetune
from tqdm.auto import tqdm

import transformers
from transformers import AutoConfig, set_seed
from transformers.trainer_utils import IntervalStrategy


_lowercase		:      Union[str, Any]					=logging.getLogger(__name__)

_lowercase		:      List[str]					="pytorch_model.bin"

@dataclasses.dataclass
class    snake_case__				:







						"""simple docstring"""




						__lowerCAmelCase     :str						=     dataclasses.field(
						    metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models."}		)
						__lowerCAmelCase     :Optional[str]						=     dataclasses.field(
						    default=__A					,	metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co."}					,	)




@dataclasses.dataclass
class    snake_case__				:







						"""simple docstring"""




						__lowerCAmelCase     :str						=     dataclasses.field(metadata={"help": "A csv or a json file containing the training data."}		)
						__lowerCAmelCase     :str						=     dataclasses.field(metadata={"help": "A csv or a json file containing the data to predict on."}		)
						__lowerCAmelCase     :Optional[str]						=     dataclasses.field(
						    default=__A					,	metadata={"help": "A csv or a json file containing the validation data."}		)
						__lowerCAmelCase     :Optional[str]						=     dataclasses.field(
						    default=__A					,	metadata={"help": "The name of the task to train on."}					,	)
						__lowerCAmelCase     :Optional[List[str]]						=     dataclasses.field(
						    default=__A					,	metadata={"help": "The list of labels for the task."}		)




@dataclasses.dataclass
class    snake_case__				:







						"""simple docstring"""




						__lowerCAmelCase     :str						=     dataclasses.field(
						    metadata={"help": "The output directory where the model predictions and checkpoints will be written."}		)
						__lowerCAmelCase     :Optional[str]						=     dataclasses.field(
						    default="accuracy"					,	metadata={"help": "The evaluation metric used for the task."}		)
						__lowerCAmelCase     :Optional[str]						=     dataclasses.field(
						    default="no"					,	metadata={
						        "help": "The evaluation strategy to adopt during training. Possible values are: [\"no\", \"step\", \"epoch]"
						    }					,	)
						__lowerCAmelCase     :Optional[int]						=     dataclasses.field(
						    default=10					,	metadata={"help": "Number of evaluation calls with no improvement after which training will be stopped."}					,	)
						__lowerCAmelCase     :Optional[float]						=     dataclasses.field(
						    default=0.0					,	metadata={
						        "help": "How much the specified evaluation metric must improve to satisfy early stopping conditions."
						    }					,	)
						__lowerCAmelCase     :Optional[bool]						=     dataclasses.field(
						    default=__A					,	metadata={"help": "Whether to filter the pseudo-labeled data based on the confidence score."}					,	)
						__lowerCAmelCase     :Optional[bool]						=     dataclasses.field(
						    default=__A					,	metadata={"help": "Whether to filter the pseudo-labeled data based on the validation performance."}					,	)
						__lowerCAmelCase     :Optional[bool]						=     dataclasses.field(
						    default=__A					,	metadata={"help": "Whether to fine-tune on labeled data after pseudo training."}					,	)
						__lowerCAmelCase     :Optional[float]						=     dataclasses.field(
						    default=0.0					,	metadata={"help": "Confidence threshold for pseudo-labeled data filtering."}					,	)
						__lowerCAmelCase     :Optional[int]						=     dataclasses.field(
						    default=100					,	metadata={"help": "Number of evaluation calls with no improvement after which training will be stopped."}					,	)
						__lowerCAmelCase     :Optional[int]						=     dataclasses.field(
						    default=__A					,	metadata={"help": "Random seed for initialization."}					,	)




def 	lowerCAmelCase_     (  _lowercase				:   Tuple						,   _lowercase				:   List[str]						,   _lowercase				:   Tuple						,   _lowercase				:   str						,   _lowercase				:   Any						,   _lowercase				:   List[Any])							->       Dict:







			"""simple docstring"""
			a__   :						Optional[int]						       =  datasets.concatenate_datasets([infer_input, infer_output]						,   axis=1)

			if args.do_filter_by_confidence:
						a__   :						Dict						       =  dataset.filter(lambda _lowercase: example["probability"] > args.confidence_threshold)

			if args.do_filter_by_val_performance:
						assert eval_result >= 0.0 and eval_result <= 1.0
						a__   :						int						       =  int(eval_result * len(_lowerCamelCase))
						print(_lowerCamelCase)
						a__   :						str						       =  dataset.sort("""probability"""						,   reverse=_lowerCamelCase)
						a__   :						str						       =  dataset.select(range(_lowerCamelCase))

			a__   :						Optional[Any]						       =  dataset.remove_columns(["""label""", """probability"""])
			a__   :						Any						       =  dataset.rename_column("""prediction"""						,   """label""")
			a__   :						Any						       =  dataset.map(lambda _lowercase: {"label": idalabel[example["label"]]})
			a__   :						List[Any]						       =  dataset.shuffle(seed=args.seed)

			a__   :						List[str]						       =  os.path.join(_lowerCamelCase						,   F'''train_pseudo.{args.data_file_extension}''')
			if args.data_file_extension == "csv":
						dataset.to_csv(_lowerCamelCase						,   index=_lowerCamelCase)
			else:
						dataset.to_json(_lowerCamelCase)





def 	lowerCAmelCase_     (  _lowercase				:   Optional[Any]						,   _lowercase				:   Any						,   _lowercase				:   Tuple						,   _lowercase				:   Optional[int]						,   **_lowercase				:   str)							->       Optional[int]:







			"""simple docstring"""
			a__   :						List[Any]						       =  Accelerator()
			# Make one log on every process with the configuration for debugging.
			logging.basicConfig(
			    format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s"""						,   datefmt="""%m/%d/%Y %H:%M:%S"""						,   level=logging.INFO						,   )
			logger.info(accelerator.state)

			# Setup logging, we only want one process per machine to log things on the
			# screen. accelerator.is_local_main_process is only True for one process per
			# machine.
			logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR)

			if accelerator.is_local_main_process:
						datasets.utils.logging.set_verbosity_warning()
						transformers.utils.logging.set_verbosity_info()
			else:
						datasets.utils.logging.set_verbosity_error()
						transformers.utils.logging.set_verbosity_error()

			a__   :						Optional[int]						       =  STModelArguments(model_name_or_path=_lowerCamelCase)
			a__   :						Dict						       =  STDataArguments(train_file=_lowerCamelCase						,   infer_file=_lowerCamelCase)
			a__   :						List[str]						       =  STTrainingArguments(output_dir=_lowerCamelCase)
			a__   :						Union[str, Any]						       =  argparse.Namespace()

			for arg_class in (model_args, data_args, training_args):
						for key, value in vars(_lowerCamelCase).items():
									setattr(_lowerCamelCase						,   _lowerCamelCase						,   _lowerCamelCase)

			for key, value in kwargs.items():
						if hasattr(_lowerCamelCase						,   _lowerCamelCase):
									setattr(_lowerCamelCase						,   _lowerCamelCase						,   _lowerCamelCase)

    # Sanity checks
			a__   :						Optional[int]						       =  {}
			a__   :						List[Any]						       =  None

			# You need to provide the training data and the data to predict on
			assert args.train_file is not None
			assert args.infer_file is not None
			a__   :						int						       =  args.train_file
			a__   :						Tuple						       =  args.infer_file

			if args.evaluation_strategy != IntervalStrategy.NO.value:
						assert args.eval_file is not None
						a__   :						List[Any]						       =  args.eval_file

			for key in data_files:
						a__   :						str						       =  data_files[key].split(""".""")[-1]
						assert extension in ["csv", "json"], F'''`{key}_file` should be a csv or a json file.'''
						if args.data_file_extension is None:
									a__   :						int						       =  extension
						else:
									assert extension == args.data_file_extension, F'''`{key}_file` should be a {args.data_file_extension} file`.'''

			assert (
			    args.eval_metric in datasets.list_metrics()
			), F'''{args.eval_metric} not in the list of supported metrics {datasets.list_metrics()}.'''

			# If passed along, set the training seed now.
			if args.seed is not None:
						set_seed(args.seed)

			logger.info("""Creating the initial data directory for self-training...""")
			a__   :						Optional[int]						       =  F'''{args.output_dir}/self-train_iter-{{}}'''.format
			a__   :						str						       =  data_dir_format(0)

			if accelerator.is_main_process:
						if args.output_dir is not None:
									os.makedirs(args.output_dir						,   exist_ok=_lowerCamelCase)
									os.makedirs(_lowerCamelCase						,   exist_ok=_lowerCamelCase)
			accelerator.wait_for_everyone()

			a__   :						Dict						       =  None
			a__   :						Union[str, Any]						       =  None
			a__   :						Union[str, Any]						       =  0
			a__   :						Tuple						       =  False
			# Show the progress bar
			a__   :						Optional[int]						       =  tqdm(range(args.max_selftrain_iterations)						,   disable=not accelerator.is_local_main_process)

			# Self-train
			for iteration in range(0						,   int(args.max_selftrain_iterations)):
						a__   :						List[str]						       =  data_dir_format(_lowerCamelCase)
						assert os.path.exists(_lowerCamelCase)

						# Stage 1: initial fine-tuning for iteration = 0 or pseudo-training for
						# iteration > 0
						a__   :						Dict						       =  os.path.join(_lowerCamelCase						,   """stage-1""")
						a__   :						List[str]						       =  {
						    "accelerator": accelerator,
						    "model_name_or_path": args.model_name_or_path,
						    "cache_dir": args.cache_dir,
						    "do_train": True,
						    "train_file": data_files["train"] if iteration == 0 else data_files["train_pseudo"],
						    "do_eval": True if args.eval_file is not None else False,
						    "eval_file": data_files["eval"],
						    "do_predict": True,
						    "infer_file": data_files["infer"],
						    "task_name": args.task_name,
						    "label_list": args.label_list,
						    "output_dir": current_output_dir,
						    "eval_metric": args.eval_metric,
						    "evaluation_strategy": args.evaluation_strategy,
						    "early_stopping_patience": args.early_stopping_patience,
						    "early_stopping_threshold": args.early_stopping_threshold,
						    "seed": args.seed,
						}
						# Add additional training arguments
						for key, value in kwargs.items():
									if key not in arguments_dict and not hasattr(_lowerCamelCase						,   _lowerCamelCase):
												arguments_dict.update({key: value})

						a__   :						Optional[Any]						       =  os.path.join(_lowerCamelCase						,   """best-checkpoint"""						,   _lowerCamelCase)
						if os.path.exists(_lowerCamelCase):
									logger.info(
									    """Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 1."""						,   _lowerCamelCase						,   _lowerCamelCase						,   )
						else:
									logger.info("""***** Running self-training: iteration: %d, stage: 1 *****"""						,   _lowerCamelCase)
									finetune(**_lowerCamelCase)
									accelerator.wait_for_everyone()
									assert os.path.exists(_lowerCamelCase)
									logger.info("""Self-training job completed: iteration: %d, stage: 1."""						,   _lowerCamelCase)

						if iteration > 0 and args.finetune_on_labeled_data:
									# Stage 2 (optional): fine-tuning on the original labeled data
									a__   :						Tuple						       =  os.path.join(_lowerCamelCase						,   """best-checkpoint""")
									a__   :						str						       =  os.path.join(_lowerCamelCase						,   """stage-2""")
									# Update arguments_dict
									a__   :						int						       =  model_path
									a__   :						List[str]						       =  data_files["train"]
									a__   :						List[str]						       =  current_output_dir

									a__   :						str						       =  os.path.join(_lowerCamelCase						,   """best-checkpoint"""						,   _lowerCamelCase)
									if os.path.exists(_lowerCamelCase):
												logger.info(
												    """Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 2."""						,   _lowerCamelCase						,   _lowerCamelCase						,   )
									else:
												logger.info("""***** Running self-training: iteration: %d, stage: 2 *****"""						,   _lowerCamelCase)
												finetune(**_lowerCamelCase)
												accelerator.wait_for_everyone()
												assert os.path.exists(_lowerCamelCase)
												logger.info("""Self-training job completed: iteration: %d, stage: 2."""						,   _lowerCamelCase)

						a__   :						Any						       =  iteration
						a__   :						List[str]						       =  data_dir_format(iteration + 1)

						a__   :						Optional[Any]						       =  AutoConfig.from_pretrained(os.path.join(_lowerCamelCase						,   """best-checkpoint"""))
						a__   :						Optional[Any]						       =  config.idalabel
						a__   :						Optional[int]						       =  os.path.join(_lowerCamelCase						,   """eval_results_best-checkpoint.json""")
						a__   :						Dict						       =  os.path.join(_lowerCamelCase						,   """test_results_best-checkpoint.json""")
						assert os.path.exists(_lowerCamelCase)

						with open(_lowerCamelCase						,   """r""") as f:
									a__   :						Dict						       =  float(json.load(_lowerCamelCase)[args.eval_metric])
						a__   :						Any						       =  os.path.join(_lowerCamelCase						,   """infer_output_best-checkpoint.csv""")
						assert os.path.exists(_lowerCamelCase)
						# Loading the dataset from local csv or json files.
						a__   :						List[Any]						       =  load_dataset(args.data_file_extension						,   data_files={"""data""": data_files["""infer"""]})["data"]
						a__   :						Tuple						       =  load_dataset("""csv"""						,   data_files={"""data""": infer_output_file})["data"]

						if accelerator.is_main_process:
									os.makedirs(_lowerCamelCase						,   exist_ok=_lowerCamelCase)
									shutil.copy(_lowerCamelCase						,   os.path.join(_lowerCamelCase						,   F'''eval_results_iter-{iteration}.json'''))
									if os.path.exists(_lowerCamelCase):
												shutil.copy(_lowerCamelCase						,   os.path.join(_lowerCamelCase						,   F'''test_results_iter-{iteration}.json'''))
									create_pseudo_labeled_data(_lowerCamelCase						,   _lowerCamelCase						,   _lowerCamelCase						,   _lowerCamelCase						,   _lowerCamelCase						,   _lowerCamelCase)
						accelerator.wait_for_everyone()

						a__   :						Dict						       =  os.path.join(_lowerCamelCase						,   F'''train_pseudo.{args.data_file_extension}''')

						if args.evaluation_strategy != IntervalStrategy.NO.value:
									a__   :						Union[str, Any]						       =  eval_result

									if best_iteration is None:
												a__   :						Union[str, Any]						       =  new_iteration
												a__   :						List[Any]						       =  new_eval_result
									else:
												if new_eval_result - best_eval_result > args.early_stopping_threshold:
															a__   :						Dict						       =  new_iteration
															a__   :						Any						       =  new_eval_result
															a__   :						str						       =  0
												else:
															if new_eval_result == best_eval_result:
																		a__   :						str						       =  new_iteration
																		a__   :						List[Any]						       =  new_eval_result
															early_stopping_patience_counter += 1

												if early_stopping_patience_counter >= args.early_stopping_patience:
															a__   :						Dict						       =  True

						progress_bar.update(1)

						if should_training_stop:
									break

			if best_iteration is not None:
						# Save the best iteration
						logger.info("""Best iteration: %d"""						,   _lowerCamelCase)
						logger.info("""Best evaluation result: %s = %f"""						,   args.eval_metric						,   _lowerCamelCase)
						accelerator.wait_for_everyone()
						if accelerator.is_main_process:
									shutil.copy(
									    os.path.join(_lowerCamelCase						,   F'''eval_results_iter-{iteration}.json''')						,   os.path.join(_lowerCamelCase						,   """eval_results_best-iteration.json""")						,   )
			else:
						# Assume that the last iteration is the best
						logger.info("""Best iteration: %d"""						,   args.max_selftrain_iterations - 1)
						logger.info("""Best evaluation result: %s = %f"""						,   args.eval_metric						,   _lowerCamelCase)
						accelerator.wait_for_everyone()
						if accelerator.is_main_process:
									shutil.copy(
									    os.path.join(_lowerCamelCase						,   F'''eval_results_iter-{args.max_selftrain_iterations - 1}.json''')						,   os.path.join(_lowerCamelCase						,   """eval_results_best-iteration.json""")						,   )





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 			lowercase_				(			_lowerCamelCase							:       Any		,	_lowerCamelCase							:       List[str]=False):
    try:
        lowercase__ :   Union[str, Any]    					=				os.environ[key]
    except KeyError:
        # KEY isn't set, default to `default`.
        lowercase__ :   int    					=				default
    else:
        # KEY is set, convert it to True or False.
        try:
            lowercase__ :   Optional[int]    					=				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  							=						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 			lowercase_				(			_lowerCamelCase							:       int):
    try:
        import faiss  # noqa
    except ImportError:
        lowercase__ :   Optional[Any]    					=				unittest.skip("test requires faiss")(_lowerCamelCase)
    return test_case

def 			lowercase_				(			_lowerCamelCase							:       int):
    try:
        import regex  # noqa
    except ImportError:
        lowercase__ :   List[Any]    					=				unittest.skip("test requires regex")(_lowerCamelCase)
    return test_case

def 			lowercase_				(			_lowerCamelCase							:       int):
    try:
        import elasticsearch  # noqa
    except ImportError:
        lowercase__ :   Optional[int]    					=				unittest.skip("test requires elasticsearch")(_lowerCamelCase)
    return test_case

def 			lowercase_				(			_lowerCamelCase							:       Union[str, Any]):
    try:
        import sqlalchemy  # noqa
    except ImportError:
        lowercase__ :   Optional[int]    					=				unittest.skip("test requires sqlalchemy")(_lowerCamelCase)
    return test_case

def 			lowercase_				(			_lowerCamelCase							:       int):
    if not config.TORCH_AVAILABLE:
        lowercase__ :   Tuple    					=				unittest.skip("test requires PyTorch")(_lowerCamelCase)
    return test_case

def 			lowercase_				(			_lowerCamelCase							:       Tuple):
    if not config.TF_AVAILABLE:
        lowercase__ :   Any    					=				unittest.skip("test requires TensorFlow")(_lowerCamelCase)
    return test_case

def 			lowercase_				(			_lowerCamelCase							:       Dict):
    if not config.JAX_AVAILABLE:
        lowercase__ :   List[str]    					=				unittest.skip("test requires JAX")(_lowerCamelCase)
    return test_case

def 			lowercase_				(			_lowerCamelCase							:       int):
    if not config.PIL_AVAILABLE:
        lowercase__ :   Dict    					=				unittest.skip("test requires Pillow")(_lowerCamelCase)
    return test_case

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

def 			lowercase_				(			_lowerCamelCase							:       Optional[Any]):
    try:
        import tiktoken  # noqa F401
    except ImportError:
        return unittest.skip("test requires tiktoken")(_lowerCamelCase)
    else:
        return test_case

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

def 			lowercase_				(			_lowerCamelCase							:       Optional[int]):

    def _require_spacy_model(_lowerCamelCase							:       Optional[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 			lowercase_				(			_lowerCamelCase							:       Dict):
    try:
        import pyspark  # noqa F401
    except ImportError:
        return unittest.skip("test requires pyspark")(_lowerCamelCase)
    else:
        return test_case

def 			lowercase_				(			_lowerCamelCase							:       List[str]):
    try:
        import joblibspark  # noqa F401
    except ImportError:
        return unittest.skip("test requires joblibspark")(_lowerCamelCase)
    else:
        return test_case

def 			lowercase_				(			_lowerCamelCase							:       Dict):
    if not _run_slow_tests or _run_slow_tests == 0:
        lowercase__ :   Tuple    					=				unittest.skip("test is slow")(_lowerCamelCase)
    return test_case

def 			lowercase_				(			_lowerCamelCase							:       int):
    if not _run_local_tests or _run_local_tests == 0:
        lowercase__ :   str    					=				unittest.skip("test is local")(_lowerCamelCase)
    return test_case

def 			lowercase_				(			_lowerCamelCase							:       Optional[int]):
    if not _run_packaged_tests or _run_packaged_tests == 0:
        lowercase__ :   List[Any]    					=				unittest.skip("test is packaged")(_lowerCamelCase)
    return test_case

def 			lowercase_				(			_lowerCamelCase							:       Tuple):
    if not _run_remote_tests or _run_remote_tests == 0:
        lowercase__ :   Union[str, Any]    					=				unittest.skip("test requires remote")(_lowerCamelCase)
    return test_case

def 			lowercase_				(			*_lowerCamelCase							:       str):
    def decorate(cls							:       str):
        for name, fn in cls.__dict__.items():
            if callable(_lowerCamelCase) and name.startswith("test"):
                for decorator in decorators:
                    lowercase__ :   Optional[int]    					=				decorator(_lowerCamelCase)
                setattr(cls		,	_lowerCamelCase		,	_lowerCamelCase)
        return cls

    return decorate



class   snake_case_       (		__A       ):
   pass



class   snake_case_       (		__A       ):
   __A	:		List[Any]         =				0
   __A	:		str         =				1
   __A	:		int         =				2



@contextmanager
def 			lowercase_				(			_lowerCamelCase							:       List[str]=OfflineSimulationMode.CONNECTION_FAILS		,	_lowerCamelCase							:       int=1E-16):
    lowercase__ :   int    					=				requests.Session().request

    def timeout_request(_lowerCamelCase							:       str		,	_lowerCamelCase							:       Dict		,	_lowerCamelCase							:       Dict		,	**_lowerCamelCase							:       str):
        # Change the url to an invalid url so that the connection hangs
        lowercase__ :   Any    					=				"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.''')
        lowercase__ :   Dict    					=				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
            lowercase__ :   Dict    					=				url
            lowercase__ :   Union[str, Any]    					=				e.args[0]
            lowercase__ :   Optional[Any]    					=				(max_retry_error.args[0].replace("10.255.255.1"		,	f'''OfflineMock[{url}]'''),)
            lowercase__ :   int    					=				(max_retry_error,)
            raise

    def raise_connection_error(_lowerCamelCase							:       Union[str, Any]		,	_lowerCamelCase							:       Optional[Any]		,	**_lowerCamelCase							:       Tuple):
        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 			lowercase_				(			*_lowerCamelCase							:       str		,	**_lowerCamelCase							:       Tuple):
    lowercase__ :   Dict    					=				str(Path().resolve())
    with tempfile.TemporaryDirectory(*_lowerCamelCase		,	**_lowerCamelCase) as tmp_dir:
        try:
            os.chdir(_lowerCamelCase)
            yield
        finally:
            os.chdir(_lowerCamelCase)

@contextmanager
def 			lowercase_				(			):
    import gc

    gc.collect()
    lowercase__ :   Union[str, Any]    					=				pa.total_allocated_bytes()
    yield
    assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."

@contextmanager
def 			lowercase_				(			):
    import gc

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

def 			lowercase_				(			_lowerCamelCase							:       Optional[Any]		,	_lowerCamelCase							:       Optional[Any]):
    return deepcopy(_lowerCamelCase).integers(0		,	100		,	10).tolist() == deepcopy(_lowerCamelCase).integers(0		,	100		,	10).tolist()

def 			lowercase_				(			_lowerCamelCase							:       str):
    import decorator
    from requests.exceptions import HTTPError

    def _wrapper(_lowerCamelCase							:       str		,	*_lowerCamelCase							:       Dict		,	**_lowerCamelCase							:       Dict):
        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   snake_case_       :






   def __init__(      self				:     int	,						lowercase_				:     Union[str, Any]	,						lowercase_				:     Dict	,						lowercase_				:     List[str]  )					->						List[str]:
       lowercase__ :   Tuple    					=				returncode
       lowercase__ :   int    					=				stdout
       lowercase__ :   Union[str, Any]    					=				stderr



async def 			lowercase_				(			_lowerCamelCase							:       List[str]		,	_lowerCamelCase							:       Dict):
    while True:
        lowercase__ :   Optional[int]    					=				await stream.readline()
        if line:
            callback(_lowerCamelCase)
        else:
            break

async def 			lowercase_				(			_lowerCamelCase							:       Optional[int]		,	_lowerCamelCase							:       Union[str, Any]=None		,	_lowerCamelCase							:       Optional[Any]=None		,	_lowerCamelCase							:       int=None		,	_lowerCamelCase							:       Optional[Any]=False		,	_lowerCamelCase							:       Tuple=False):
    if echo:
        print("\nRunning: "		,	" ".join(_lowerCamelCase))

    lowercase__ :   Optional[int]    					=				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)

    lowercase__ :   str    					=				[]
    lowercase__ :   List[str]    					=				[]

    def tee(_lowerCamelCase							:       str		,	_lowerCamelCase							:       Optional[Any]		,	_lowerCamelCase							:       Union[str, Any]		,	_lowerCamelCase							:       Optional[int]=""):
        lowercase__ :   Optional[int]    					=				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 			lowercase_				(			_lowerCamelCase							:       Optional[int]		,	_lowerCamelCase							:       List[str]=None		,	_lowerCamelCase							:       Dict=None		,	_lowerCamelCase							:       int=180		,	_lowerCamelCase							:       Union[str, Any]=False		,	_lowerCamelCase							:       Optional[Any]=True):
    lowercase__ :   Any    					=				asyncio.get_event_loop()
    lowercase__ :   Tuple    					=				loop.run_until_complete(
        _stream_subprocess(_lowerCamelCase		,	env=_lowerCamelCase		,	stdin=_lowerCamelCase		,	timeout=_lowerCamelCase		,	quiet=_lowerCamelCase		,	echo=_lowerCamelCase))

    lowercase__ :   int    					=				" ".join(_lowerCamelCase)
    if result.returncode > 0:
        lowercase__ :   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}''')

    # 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 			lowercase_				(			):
    lowercase__ :   List[str]    					=				os.environ.get("PYTEST_XDIST_WORKER"		,	"gw0")
    lowercase__ :   str    					=				re.sub(R"^gw"		,	""		,	_lowerCamelCase		,	0		,	re.M)
    return int(_lowerCamelCase)

def 			lowercase_				(			):
    lowercase__ :   Union[str, Any]    					=				2_9500
    lowercase__ :   Optional[int]    					=				pytest_xdist_worker_id()
    return port + uniq_delta



