





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


_lowerCamelCase      							=   parse_flag_from_env('RUN_SLOW', default=False)
_lowerCamelCase      							=   parse_flag_from_env('RUN_REMOTE', default=False)
_lowerCamelCase      							=   parse_flag_from_env('RUN_LOCAL', default=True)
_lowerCamelCase      							=   parse_flag_from_env('RUN_PACKAGED', default=True)

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

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

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




def  __UpperCAmelCase(   lowercase_   ):
       try:
              import faiss  # noqa
       except ImportError:
              _lowerCamelCase				:  List[Any]						=		unittest.skip('''test requires faiss'''   )(lowercase_   )
       return test_case




def  __UpperCAmelCase(   lowercase_   ):
       try:
              import regex  # noqa
       except ImportError:
              _lowerCamelCase				:  Optional[Any]						=		unittest.skip('''test requires regex'''   )(lowercase_   )
       return test_case




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




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




def  __UpperCAmelCase(   lowercase_   ):
       if not config.TORCH_AVAILABLE:
              _lowerCamelCase				:  str						=		unittest.skip('''test requires PyTorch'''   )(lowercase_   )
       return test_case




def  __UpperCAmelCase(   lowercase_   ):
       if not config.TF_AVAILABLE:
              _lowerCamelCase				:  Union[str, Any]						=		unittest.skip('''test requires TensorFlow'''   )(lowercase_   )
       return test_case




def  __UpperCAmelCase(   lowercase_   ):
       if not config.JAX_AVAILABLE:
              _lowerCamelCase				:  List[Any]						=		unittest.skip('''test requires JAX'''   )(lowercase_   )
       return test_case




def  __UpperCAmelCase(   lowercase_   ):
       if not config.PIL_AVAILABLE:
              _lowerCamelCase				:  Tuple						=		unittest.skip('''test requires Pillow'''   )(lowercase_   )
       return test_case




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




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




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




def  __UpperCAmelCase(   lowercase_   ):

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

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

       return _require_spacy_model




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




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




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




def  __UpperCAmelCase(   lowercase_   ):
       if not _run_local_tests or _run_local_tests == 0:
              _lowerCamelCase				:  List[Any]						=		unittest.skip('''test is local'''   )(lowercase_   )
       return test_case




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




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




def  __UpperCAmelCase(   *lowercase_   ):
       def decorate(cls   ):
              for name, fn in cls.__dict__.items():
                     if callable(lowercase_   ) and name.startswith('''test'''   ):
                            for decorator in decorators:
                                   _lowerCamelCase				:  Any						=		decorator(lowercase_   )
                            setattr(cls			,     lowercase_			,     lowercase_   )
              return cls

       return decorate







class       __A							(   lowerCamelCase__	):




      """simple docstring"""







      pass







class       __A							(   lowerCamelCase__	):




      """simple docstring"""







      UpperCAmelCase__							=   0
      UpperCAmelCase__							=   1
      UpperCAmelCase__							=   2




@contextmanager
def  __UpperCAmelCase(   lowercase_=OfflineSimulationMode.CONNECTION_FAILS			,     lowercase_=1e-16   ):
       _lowerCamelCase				:  Union[str, Any]						=		requests.Session().request

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

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

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




@contextmanager
def  __UpperCAmelCase(   *lowercase_			,     **lowercase_   ):
       _lowerCamelCase				:  int						=		str(Path().resolve()   )
       with tempfile.TemporaryDirectory(*lowercase_			,     **lowercase_   ) as tmp_dir:
              try:
                     os.chdir(lowercase_   )
                     yield
              finally:
                     os.chdir(lowercase_   )




@contextmanager
def  __UpperCAmelCase(   ):
       import gc

       gc.collect()
       _lowerCamelCase				:  Optional[int]						=		pa.total_allocated_bytes()
       yield
       assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."




@contextmanager
def  __UpperCAmelCase(   ):
       import gc

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




def  __UpperCAmelCase(   lowercase_			,     lowercase_   ):
       return deepcopy(lowercase_   ).integers(0			,     1_00			,     10   ).tolist() == deepcopy(lowercase_   ).integers(0			,     1_00			,     10   ).tolist()




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

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

       return decorator.decorator(_wrapper			,     lowercase_   )







class       __A							:




      """simple docstring"""







      def __init__(		self   ,				a__   ,				a__   ,				a__):



             """simple docstring"""





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




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




async def  __UpperCAmelCase(   lowercase_			,     lowercase_=None			,     lowercase_=None			,     lowercase_=None			,     lowercase_=False			,     lowercase_=False   ):
       if echo:
              print('''\nRunning: '''			,     ''' '''.join(lowercase_   )   )

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

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

       _lowerCamelCase				:  Any						=		[]
       _lowerCamelCase				:  Dict						=		[]

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

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




def  __UpperCAmelCase(   lowercase_			,     lowercase_=None			,     lowercase_=None			,     lowercase_=1_80			,     lowercase_=False			,     lowercase_=True   ):
       _lowerCamelCase				:  Any						=		asyncio.get_event_loop()
       _lowerCamelCase				:  str						=		loop.run_until_complete(
           _stream_subprocess(lowercase_			,     env=lowercase_			,     stdin=lowercase_			,     timeout=lowercase_			,     quiet=lowercase_			,     echo=lowercase_   )   )

       _lowerCamelCase				:  Optional[Any]						=		''' '''.join(lowercase_   )
       if result.returncode > 0:
              _lowerCamelCase				:  int						=		'''\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(   ):
       _lowerCamelCase				:  Tuple						=		os.environ.get('''PYTEST_XDIST_WORKER'''			,     '''gw0'''   )
       _lowerCamelCase				:  Optional[Any]						=		re.sub(r'''^gw'''			,     ''''''			,     lowercase_			,     0			,     re.M   )
       return int(lowercase_   )




def  __UpperCAmelCase(   ):
       _lowerCamelCase				:  Union[str, Any]						=		2_95_00
       _lowerCamelCase				:  Union[str, Any]						=		pytest_xdist_worker_id()
       return port + uniq_delta








import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers.testing_utils import require_vision
from transformers.utils import is_vision_available


if is_vision_available():
       from PIL import Image

       from transformers import (
           AutoProcessor,
           BertTokenizerFast,
           BlipImageProcessor,
           GPTaTokenizer,
           InstructBlipProcessor,
           PreTrainedTokenizerFast,
       )







@require_vision
class       __A							(   unittest.TestCase	):




      """simple docstring"""







      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  List[Any]						=		tempfile.mkdtemp()

             _lowerCamelCase				:  List[str]						=		BlipImageProcessor()
             _lowerCamelCase				:  Union[str, Any]						=		GPTaTokenizer.from_pretrained('''hf-internal-testing/tiny-random-GPT2Model''')
             _lowerCamelCase				:  Any						=		BertTokenizerFast.from_pretrained('''hf-internal-testing/tiny-random-bert''')

             _lowerCamelCase				:  Any						=		InstructBlipProcessor(a__   ,				a__   ,				a__)

             processor.save_pretrained(self.tmpdirname)


      def 					__snake_case      (		self   ,				**a__):



             """simple docstring"""





             return AutoProcessor.from_pretrained(self.tmpdirname   ,				**a__).tokenizer


      def 					__snake_case      (		self   ,				**a__):



             """simple docstring"""





             return AutoProcessor.from_pretrained(self.tmpdirname   ,				**a__).image_processor


      def 					__snake_case      (		self   ,				**a__):



             """simple docstring"""





             return AutoProcessor.from_pretrained(self.tmpdirname   ,				**a__).qformer_tokenizer


      def 					__snake_case      (		self):



             """simple docstring"""





             shutil.rmtree(self.tmpdirname)


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  List[Any]						=		[np.random.randint(255   ,				size=(3, 30, 400)   ,				dtype=np.uinta)]

             _lowerCamelCase				:  List[str]						=		[Image.fromarray(np.moveaxis(a__   ,				0   ,				-1)) for x in image_inputs]

             return image_inputs


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  Optional[Any]						=		InstructBlipProcessor(
                 tokenizer=self.get_tokenizer()   ,				image_processor=self.get_image_processor()   ,				qformer_tokenizer=self.get_qformer_tokenizer()   ,				)
             processor.save_pretrained(self.tmpdirname)

             _lowerCamelCase				:  Optional[int]						=		self.get_tokenizer(bos_token='''(BOS)'''   ,				eos_token='''(EOS)''')
             _lowerCamelCase				:  str						=		self.get_image_processor(do_normalize=a__   ,				padding_value=1.0)

             _lowerCamelCase				:  Tuple						=		InstructBlipProcessor.from_pretrained(
                 self.tmpdirname   ,				bos_token='''(BOS)'''   ,				eos_token='''(EOS)'''   ,				do_normalize=a__   ,				padding_value=1.0)

             self.assertEqual(processor.tokenizer.get_vocab()   ,				tokenizer_add_kwargs.get_vocab())
             self.assertIsInstance(processor.tokenizer   ,				a__)

             self.assertEqual(processor.image_processor.to_json_string()   ,				image_processor_add_kwargs.to_json_string())
             self.assertIsInstance(processor.image_processor   ,				a__)
             self.assertIsInstance(processor.qformer_tokenizer   ,				a__)


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  List[str]						=		self.get_image_processor()
             _lowerCamelCase				:  Optional[int]						=		self.get_tokenizer()
             _lowerCamelCase				:  Any						=		self.get_qformer_tokenizer()

             _lowerCamelCase				:  Dict						=		InstructBlipProcessor(
                 tokenizer=a__   ,				image_processor=a__   ,				qformer_tokenizer=a__)

             _lowerCamelCase				:  List[Any]						=		self.prepare_image_inputs()

             _lowerCamelCase				:  List[str]						=		image_processor(a__   ,				return_tensors='''np''')
             _lowerCamelCase				:  List[Any]						=		processor(images=a__   ,				return_tensors='''np''')

             for key in input_feat_extract.keys():
                    self.assertAlmostEqual(input_feat_extract[key].sum()   ,				input_processor[key].sum()   ,				delta=1e-2)


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  Any						=		self.get_image_processor()
             _lowerCamelCase				:  Dict						=		self.get_tokenizer()
             _lowerCamelCase				:  int						=		self.get_qformer_tokenizer()

             _lowerCamelCase				:  Tuple						=		InstructBlipProcessor(
                 tokenizer=a__   ,				image_processor=a__   ,				qformer_tokenizer=a__)

             _lowerCamelCase				:  List[Any]						=		'''lower newer'''

             _lowerCamelCase				:  Any						=		processor(text=a__)

             _lowerCamelCase				:  Optional[int]						=		tokenizer(a__   ,				return_token_type_ids=a__)
             _lowerCamelCase				:  Optional[Any]						=		qformer_tokenizer(a__   ,				return_token_type_ids=a__)

             for key in encoded_tokens.keys():
                    self.assertListEqual(encoded_tokens[key]   ,				encoded_processor[key])

             for key in encoded_tokens_qformer.keys():
                    self.assertListEqual(encoded_tokens_qformer[key]   ,				encoded_processor['''qformer_''' + key])


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  List[Any]						=		self.get_image_processor()
             _lowerCamelCase				:  Optional[int]						=		self.get_tokenizer()
             _lowerCamelCase				:  Optional[Any]						=		self.get_qformer_tokenizer()

             _lowerCamelCase				:  List[Any]						=		InstructBlipProcessor(
                 tokenizer=a__   ,				image_processor=a__   ,				qformer_tokenizer=a__)

             _lowerCamelCase				:  List[Any]						=		'''lower newer'''
             _lowerCamelCase				:  Tuple						=		self.prepare_image_inputs()

             _lowerCamelCase				:  Tuple						=		processor(text=a__   ,				images=a__)

             self.assertListEqual(
                 list(inputs.keys())   ,				['''input_ids''', '''attention_mask''', '''qformer_input_ids''', '''qformer_attention_mask''', '''pixel_values''']   ,				)

             # test if it raises when no input is passed
             with pytest.raises(a__):
                    processor()


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  int						=		self.get_image_processor()
             _lowerCamelCase				:  List[Any]						=		self.get_tokenizer()
             _lowerCamelCase				:  List[Any]						=		self.get_qformer_tokenizer()

             _lowerCamelCase				:  Optional[Any]						=		InstructBlipProcessor(
                 tokenizer=a__   ,				image_processor=a__   ,				qformer_tokenizer=a__)

             _lowerCamelCase				:  List[Any]						=		[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

             _lowerCamelCase				:  Tuple						=		processor.batch_decode(a__)
             _lowerCamelCase				:  str						=		tokenizer.batch_decode(a__)

             self.assertListEqual(a__   ,				a__)



      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  List[str]						=		self.get_image_processor()
             _lowerCamelCase				:  Dict						=		self.get_tokenizer()
             _lowerCamelCase				:  str						=		self.get_qformer_tokenizer()

             _lowerCamelCase				:  str						=		InstructBlipProcessor(
                 tokenizer=a__   ,				image_processor=a__   ,				qformer_tokenizer=a__)

             _lowerCamelCase				:  str						=		'''lower newer'''
             _lowerCamelCase				:  str						=		self.prepare_image_inputs()

             _lowerCamelCase				:  List[Any]						=		processor(text=a__   ,				images=a__)

             self.assertListEqual(
                 list(inputs.keys())   ,				['''input_ids''', '''attention_mask''', '''qformer_input_ids''', '''qformer_attention_mask''', '''pixel_values''']   ,				)

