

'''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__		(    SCREAMING_SNAKE_CASE   : str							, SCREAMING_SNAKE_CASE   : int=False    ):
  try:
    UpperCAmelCase    				=						os.environ[key]
  except KeyError:
    # KEY isn't set, default to `default`.
    UpperCAmelCase    				=						default
  else:
    # KEY is set, convert it to True or False.
    try:
      UpperCAmelCase    				=						strtobool(SCREAMING_SNAKE_CASE    )
    except ValueError:
      # More values are supported, but let's keep the message simple.
      raise ValueError(f'''If set, {key} must be yes or no.'''    )
  return _value


_a					:			List[str]							=    parse_flag_from_env('RUN_SLOW', default=False)
_a					:			Union[str, Any]							=    parse_flag_from_env('RUN_REMOTE', default=False)
_a					:			Dict							=    parse_flag_from_env('RUN_LOCAL', default=True)
_a					:			Tuple							=    parse_flag_from_env('RUN_PACKAGED', default=True)

# Compression
_a					:			Union[str, Any]							=    pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='test requires lz4')
_a					:			Union[str, Any]							=    pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='test requires py7zr')
_a					:			Union[str, Any]							=    pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='test requires zstandard')

# Audio
_a					:			Dict							=    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
_a					:			str							=    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
_a					:			Optional[int]							=    pytest.mark.skipif(
    config.DILL_VERSION <= version.parse('0.3.2'),
    reason='test requires dill>0.3.2 for cloudpickle compatibility',
)

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


def    lowerCamelCase__		(    SCREAMING_SNAKE_CASE   : Any    ):
  try:
    import faiss  # noqa
  except ImportError:
    UpperCAmelCase    				=						unittest.skip('test requires faiss'    )(SCREAMING_SNAKE_CASE    )
  return test_case


def    lowerCamelCase__		(    SCREAMING_SNAKE_CASE   : str    ):
  try:
    import regex  # noqa
  except ImportError:
    UpperCAmelCase    				=						unittest.skip('test requires regex'    )(SCREAMING_SNAKE_CASE    )
  return test_case


def    lowerCamelCase__		(    SCREAMING_SNAKE_CASE   : Optional[Any]    ):
  try:
    import elasticsearch  # noqa
  except ImportError:
    UpperCAmelCase    				=						unittest.skip('test requires elasticsearch'    )(SCREAMING_SNAKE_CASE    )
  return test_case


def    lowerCamelCase__		(    SCREAMING_SNAKE_CASE   : Any    ):
  try:
    import sqlalchemy  # noqa
  except ImportError:
    UpperCAmelCase    				=						unittest.skip('test requires sqlalchemy'    )(SCREAMING_SNAKE_CASE    )
  return test_case


def    lowerCamelCase__		(    SCREAMING_SNAKE_CASE   : Any    ):
  if not config.TORCH_AVAILABLE:
    UpperCAmelCase    				=						unittest.skip('test requires PyTorch'    )(SCREAMING_SNAKE_CASE    )
  return test_case


def    lowerCamelCase__		(    SCREAMING_SNAKE_CASE   : int    ):
  if not config.TF_AVAILABLE:
    UpperCAmelCase    				=						unittest.skip('test requires TensorFlow'    )(SCREAMING_SNAKE_CASE    )
  return test_case


def    lowerCamelCase__		(    SCREAMING_SNAKE_CASE   : Optional[int]    ):
  if not config.JAX_AVAILABLE:
    UpperCAmelCase    				=						unittest.skip('test requires JAX'    )(SCREAMING_SNAKE_CASE    )
  return test_case


def    lowerCamelCase__		(    SCREAMING_SNAKE_CASE   : Union[str, Any]    ):
  if not config.PIL_AVAILABLE:
    UpperCAmelCase    				=						unittest.skip('test requires Pillow'    )(SCREAMING_SNAKE_CASE    )
  return test_case


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


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


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


def    lowerCamelCase__		(    SCREAMING_SNAKE_CASE   : Union[str, Any]    ):

  def _require_spacy_model(SCREAMING_SNAKE_CASE   : Tuple    ):
    try:
      import spacy  # noqa F401

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

  return _require_spacy_model


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


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


def    lowerCamelCase__		(    SCREAMING_SNAKE_CASE   : str    ):
  if not _run_slow_tests or _run_slow_tests == 0:
    UpperCAmelCase    				=						unittest.skip('test is slow'    )(SCREAMING_SNAKE_CASE    )
  return test_case


def    lowerCamelCase__		(    SCREAMING_SNAKE_CASE   : Dict    ):
  if not _run_local_tests or _run_local_tests == 0:
    UpperCAmelCase    				=						unittest.skip('test is local'    )(SCREAMING_SNAKE_CASE    )
  return test_case


def    lowerCamelCase__		(    SCREAMING_SNAKE_CASE   : Union[str, Any]    ):
  if not _run_packaged_tests or _run_packaged_tests == 0:
    UpperCAmelCase    				=						unittest.skip('test is packaged'    )(SCREAMING_SNAKE_CASE    )
  return test_case


def    lowerCamelCase__		(    SCREAMING_SNAKE_CASE   : Dict    ):
  if not _run_remote_tests or _run_remote_tests == 0:
    UpperCAmelCase    				=						unittest.skip('test requires remote'    )(SCREAMING_SNAKE_CASE    )
  return test_case


def    lowerCamelCase__		(    *SCREAMING_SNAKE_CASE   : Optional[int]    ):
  def decorate(cls   : Union[str, Any]    ):
    for name, fn in cls.__dict__.items():
      if callable(SCREAMING_SNAKE_CASE    ) and name.startswith('test'    ):
        for decorator in decorators:
          UpperCAmelCase    				=						decorator(SCREAMING_SNAKE_CASE    )
        setattr(cls							, SCREAMING_SNAKE_CASE							, SCREAMING_SNAKE_CASE    )
    return cls

  return decorate



class 							lowercase_						(		a			):

  '''simple docstring'''





  pass




class 							lowercase_						(		a			):

  '''simple docstring'''





  __lowerCAmelCase       :			Optional[Any]     	= 0
  __lowerCAmelCase       :			Optional[Any]     	= 1
  __lowerCAmelCase       :			Tuple     	= 2




@contextmanager
def    lowerCamelCase__		(    SCREAMING_SNAKE_CASE   : List[Any]=OfflineSimulationMode.CONNECTION_FAILS							, SCREAMING_SNAKE_CASE   : Any=1E-16    ):
  UpperCAmelCase    				=						requests.Session().request

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

  def raise_connection_error(SCREAMING_SNAKE_CASE   : List[str]							, SCREAMING_SNAKE_CASE   : Dict							, **SCREAMING_SNAKE_CASE   : List[str]    ):
    raise requests.ConnectionError('Offline mode is enabled.'							, request=SCREAMING_SNAKE_CASE    )

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


@contextmanager
def    lowerCamelCase__		(    *SCREAMING_SNAKE_CASE   : Tuple							, **SCREAMING_SNAKE_CASE   : int    ):
  UpperCAmelCase    				=						str(Path().resolve()    )
  with tempfile.TemporaryDirectory(*SCREAMING_SNAKE_CASE							, **SCREAMING_SNAKE_CASE    ) as tmp_dir:
    try:
      os.chdir(SCREAMING_SNAKE_CASE    )
      yield
    finally:
      os.chdir(SCREAMING_SNAKE_CASE    )


@contextmanager
def    lowerCamelCase__		(    ):
  import gc

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


@contextmanager
def    lowerCamelCase__		(    ):
  import gc

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


def    lowerCamelCase__		(    SCREAMING_SNAKE_CASE   : Any							, SCREAMING_SNAKE_CASE   : int    ):
  return deepcopy(SCREAMING_SNAKE_CASE    ).integers(0							, 100							, 10    ).tolist() == deepcopy(SCREAMING_SNAKE_CASE    ).integers(0							, 100							, 10    ).tolist()


def    lowerCamelCase__		(    SCREAMING_SNAKE_CASE   : Any    ):
  import decorator
  from requests.exceptions import HTTPError

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

  return decorator.decorator(_wrapper							, SCREAMING_SNAKE_CASE    )



class 							lowercase_						:

  '''simple docstring'''





  def __init__(  self ,			a_ ,			a_ ,			a_  )				->					str:


    """simple docstring"""
    UpperCAmelCase    				=						returncode
    UpperCAmelCase    				=						stdout
    UpperCAmelCase    				=						stderr




async def    lowerCamelCase__		(    SCREAMING_SNAKE_CASE   : List[str]							, SCREAMING_SNAKE_CASE   : Union[str, Any]    ):
  while True:
    UpperCAmelCase    				=						await stream.readline()
    if line:
      callback(SCREAMING_SNAKE_CASE    )
    else:
      break


async def    lowerCamelCase__		(    SCREAMING_SNAKE_CASE   : Optional[int]							, SCREAMING_SNAKE_CASE   : Optional[Any]=None							, SCREAMING_SNAKE_CASE   : str=None							, SCREAMING_SNAKE_CASE   : Optional[int]=None							, SCREAMING_SNAKE_CASE   : str=False							, SCREAMING_SNAKE_CASE   : int=False    ):
  if echo:
    print('\nRunning: '							, ' '.join(SCREAMING_SNAKE_CASE    )    )

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

  # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
  # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
  #
  # If it starts hanging, will need to switch to the following code. The problem is that no data
  # will be seen until it's done and if it hangs for example there will be no debug info.
  # out, err = await p.communicate()
  # return _RunOutput(p.returncode, out, err)

  UpperCAmelCase    				=						[]
  UpperCAmelCase    				=						[]

  def tee(SCREAMING_SNAKE_CASE   : Optional[Any]							, SCREAMING_SNAKE_CASE   : Any							, SCREAMING_SNAKE_CASE   : List[str]							, SCREAMING_SNAKE_CASE   : List[str]=""    ):
    UpperCAmelCase    				=						line.decode('utf-8'    ).rstrip()
    sink.append(SCREAMING_SNAKE_CASE    )
    if not quiet:
      print(SCREAMING_SNAKE_CASE							, SCREAMING_SNAKE_CASE							, file=SCREAMING_SNAKE_CASE    )

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


def    lowerCamelCase__		(    SCREAMING_SNAKE_CASE   : List[Any]							, SCREAMING_SNAKE_CASE   : Any=None							, SCREAMING_SNAKE_CASE   : Dict=None							, SCREAMING_SNAKE_CASE   : int=180							, SCREAMING_SNAKE_CASE   : Tuple=False							, SCREAMING_SNAKE_CASE   : Any=True    ):
  UpperCAmelCase    				=						asyncio.get_event_loop()
  UpperCAmelCase    				=						loop.run_until_complete(
      _stream_subprocess(SCREAMING_SNAKE_CASE							, env=SCREAMING_SNAKE_CASE							, stdin=SCREAMING_SNAKE_CASE							, timeout=SCREAMING_SNAKE_CASE							, quiet=SCREAMING_SNAKE_CASE							, echo=SCREAMING_SNAKE_CASE    )    )

  UpperCAmelCase    				=						' '.join(SCREAMING_SNAKE_CASE    )
  if result.returncode > 0:
    UpperCAmelCase    				=						'\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__		(    ):
  UpperCAmelCase    				=						os.environ.get('PYTEST_XDIST_WORKER'							, 'gw0'    )
  UpperCAmelCase    				=						re.sub(R'^gw'							, ''							, SCREAMING_SNAKE_CASE							, 0							, re.M    )
  return int(SCREAMING_SNAKE_CASE    )



def    lowerCamelCase__		(    ):
  UpperCAmelCase    				=						2_9500
  UpperCAmelCase    				=						pytest_xdist_worker_id()
  return port + uniq_delta





'''simple docstring'''




import subprocess
import sys

from transformers import BertConfig, BertModel, BertTokenizer, pipeline
from transformers.testing_utils import TestCasePlus, require_torch



class 							lowercase_						(		a			):

  '''simple docstring'''





  @require_torch
  def     snake_case_      (  self  )				->					Optional[Any]:


    """simple docstring"""
    # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before
    # `transformers` is loaded, and it's too late for inside pytest - so we are changing it
    # while running an external program

    # python one-liner segments

    # this must be loaded before socket.socket is monkey-patched
    UpperCAmelCase    				=						'\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n        '

    UpperCAmelCase    				=						'\nmname = "hf-internal-testing/tiny-random-bert"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task="fill-mask", model=mname)\nprint("success")\n        '

    UpperCAmelCase    				=						'\nimport socket\ndef offline_socket(*args, **kwargs): raise RuntimeError("Offline mode is enabled, we shouldn\'t access internet")\nsocket.socket = offline_socket\n        '

    # Force fetching the files so that we can use the cache
    UpperCAmelCase    				=						'hf-internal-testing/tiny-random-bert'
    BertConfig.from_pretrained(a_  )
    BertModel.from_pretrained(a_  )
    BertTokenizer.from_pretrained(a_  )
    pipeline(task='fill-mask' ,			model=a_  )

    # baseline - just load from_pretrained with normal network
    UpperCAmelCase    				=						[sys.executable, '-c', '\n'.join([load, run, mock]  )]

    # should succeed
    UpperCAmelCase    				=						self.get_env()
    # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
    UpperCAmelCase    				=						'1'
    UpperCAmelCase    				=						subprocess.run(a_ ,			env=a_ ,			check=a_ ,			capture_output=a_  )
    self.assertEqual(result.returncode ,			0 ,			result.stderr  )
    self.assertIn('success' ,			result.stdout.decode()  )
  @require_torch
  def     snake_case_      (  self  )				->					Union[str, Any]:


    """simple docstring"""
    # python one-liner segments
    # this must be loaded before socket.socket is monkey-patched
    UpperCAmelCase    				=						'\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n        '

    UpperCAmelCase    				=						'\nmname = "hf-internal-testing/tiny-random-bert"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task="fill-mask", model=mname)\nprint("success")\n        '

    UpperCAmelCase    				=						'\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error("Faking flaky internet")\nsocket.socket = offline_socket\n        '

    # Force fetching the files so that we can use the cache
    UpperCAmelCase    				=						'hf-internal-testing/tiny-random-bert'
    BertConfig.from_pretrained(a_  )
    BertModel.from_pretrained(a_  )
    BertTokenizer.from_pretrained(a_  )
    pipeline(task='fill-mask' ,			model=a_  )

    # baseline - just load from_pretrained with normal network
    UpperCAmelCase    				=						[sys.executable, '-c', '\n'.join([load, run, mock]  )]

    # should succeed
    UpperCAmelCase    				=						self.get_env()
    UpperCAmelCase    				=						subprocess.run(a_ ,			env=a_ ,			check=a_ ,			capture_output=a_  )
    self.assertEqual(result.returncode ,			0 ,			result.stderr  )
    self.assertIn('success' ,			result.stdout.decode()  )
  @require_torch
  def     snake_case_      (  self  )				->					List[str]:


    """simple docstring"""
    # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before
    # `transformers` is loaded, and it's too late for inside pytest - so we are changing it
    # while running an external program

    # python one-liner segments

    # this must be loaded before socket.socket is monkey-patched
    UpperCAmelCase    				=						'\nfrom transformers import BertConfig, BertModel, BertTokenizer\n        '

    UpperCAmelCase    				=						'\nmname = "hf-internal-testing/tiny-random-bert-sharded"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nprint("success")\n        '

    UpperCAmelCase    				=						'\nimport socket\ndef offline_socket(*args, **kwargs): raise ValueError("Offline mode is enabled")\nsocket.socket = offline_socket\n        '

    # baseline - just load from_pretrained with normal network
    UpperCAmelCase    				=						[sys.executable, '-c', '\n'.join([load, run]  )]

    # should succeed
    UpperCAmelCase    				=						self.get_env()
    UpperCAmelCase    				=						subprocess.run(a_ ,			env=a_ ,			check=a_ ,			capture_output=a_  )
    self.assertEqual(result.returncode ,			0 ,			result.stderr  )
    self.assertIn('success' ,			result.stdout.decode()  )

    # next emulate no network
    UpperCAmelCase    				=						[sys.executable, '-c', '\n'.join([load, mock, run]  )]

    # Doesn't fail anymore since the model is in the cache due to other tests, so commenting this.
    # env["TRANSFORMERS_OFFLINE"] = "0"
    # result = subprocess.run(cmd, env=env, check=False, capture_output=True)
    # self.assertEqual(result.returncode, 1, result.stderr)

    # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
    UpperCAmelCase    				=						'1'
    UpperCAmelCase    				=						subprocess.run(a_ ,			env=a_ ,			check=a_ ,			capture_output=a_  )
    self.assertEqual(result.returncode ,			0 ,			result.stderr  )
    self.assertIn('success' ,			result.stdout.decode()  )
  @require_torch
  def     snake_case_      (  self  )				->					Optional[Any]:


    """simple docstring"""
    UpperCAmelCase    				=						'\nfrom transformers import pipeline\n        '
    UpperCAmelCase    				=						'\nmname = "hf-internal-testing/tiny-random-bert"\npipe = pipeline(model=mname)\n        '

    UpperCAmelCase    				=						'\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error("Offline mode is enabled")\nsocket.socket = offline_socket\n        '
    UpperCAmelCase    				=						self.get_env()
    UpperCAmelCase    				=						'1'
    UpperCAmelCase    				=						[sys.executable, '-c', '\n'.join([load, mock, run]  )]
    UpperCAmelCase    				=						subprocess.run(a_ ,			env=a_ ,			check=a_ ,			capture_output=a_  )
    self.assertEqual(result.returncode ,			1 ,			result.stderr  )
    self.assertIn(
        'You cannot infer task automatically within `pipeline` when using offline mode' ,			result.stderr.decode().replace('\n' ,			''  ) ,			)





  @require_torch
  def     snake_case_      (  self  )				->					str:


    """simple docstring"""
    UpperCAmelCase    				=						'\nfrom transformers import AutoModel\n        '
    UpperCAmelCase    				=						'\nmname = "hf-internal-testing/test_dynamic_model"\nAutoModel.from_pretrained(mname, trust_remote_code=True)\nprint("success")\n        '

    # baseline - just load from_pretrained with normal network
    UpperCAmelCase    				=						[sys.executable, '-c', '\n'.join([load, run]  )]

    # should succeed
    UpperCAmelCase    				=						self.get_env()
    UpperCAmelCase    				=						subprocess.run(a_ ,			env=a_ ,			check=a_ ,			capture_output=a_  )
    self.assertEqual(result.returncode ,			0 ,			result.stderr  )
    self.assertIn('success' ,			result.stdout.decode()  )

    # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
    UpperCAmelCase    				=						'1'
    UpperCAmelCase    				=						subprocess.run(a_ ,			env=a_ ,			check=a_ ,			capture_output=a_  )
    self.assertEqual(result.returncode ,			0 ,			result.stderr  )
    self.assertIn('success' ,			result.stdout.decode()  )


