



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						(				__lowerCamelCase   :     List[Any]		,	__lowerCamelCase   :     Dict=False     ):



 """simple docstring"""





 try:
  __SCREAMING_SNAKE_CASE       :    List[str]       =	os.environ[key]
 except KeyError:
  # KEY isn't set, default to `default`.
  __SCREAMING_SNAKE_CASE       :    List[str]       =	default
 else:
  # KEY is set, convert it to True or False.
  try:
   __SCREAMING_SNAKE_CASE       :    List[str]       =	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


_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 	_lowerCAmelCase						(				__lowerCamelCase   :     List[str]     ):



 """simple docstring"""





 try:
  import faiss  # noqa
 except ImportError:
  __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	unittest.skip("test requires faiss"     )(__lowerCamelCase     )
 return test_case






def 	_lowerCAmelCase						(				__lowerCamelCase   :     Any     ):



 """simple docstring"""





 try:
  import regex  # noqa
 except ImportError:
  __SCREAMING_SNAKE_CASE       :    List[Any]       =	unittest.skip("test requires regex"     )(__lowerCamelCase     )
 return test_case






def 	_lowerCAmelCase						(				__lowerCamelCase   :     Dict     ):



 """simple docstring"""





 try:
  import elasticsearch  # noqa
 except ImportError:
  __SCREAMING_SNAKE_CASE       :    Optional[int]       =	unittest.skip("test requires elasticsearch"     )(__lowerCamelCase     )
 return test_case






def 	_lowerCAmelCase						(				__lowerCamelCase   :     Optional[Any]     ):



 """simple docstring"""





 try:
  import sqlalchemy  # noqa
 except ImportError:
  __SCREAMING_SNAKE_CASE       :    Dict       =	unittest.skip("test requires sqlalchemy"     )(__lowerCamelCase     )
 return test_case






def 	_lowerCAmelCase						(				__lowerCamelCase   :     Union[str, Any]     ):



 """simple docstring"""





 if not config.TORCH_AVAILABLE:
  __SCREAMING_SNAKE_CASE       :    Optional[int]       =	unittest.skip("test requires PyTorch"     )(__lowerCamelCase     )
 return test_case






def 	_lowerCAmelCase						(				__lowerCamelCase   :     Tuple     ):



 """simple docstring"""





 if not config.TF_AVAILABLE:
  __SCREAMING_SNAKE_CASE       :    List[Any]       =	unittest.skip("test requires TensorFlow"     )(__lowerCamelCase     )
 return test_case






def 	_lowerCAmelCase						(				__lowerCamelCase   :     Optional[int]     ):



 """simple docstring"""





 if not config.JAX_AVAILABLE:
  __SCREAMING_SNAKE_CASE       :    Dict       =	unittest.skip("test requires JAX"     )(__lowerCamelCase     )
 return test_case






def 	_lowerCAmelCase						(				__lowerCamelCase   :     Dict     ):



 """simple docstring"""





 if not config.PIL_AVAILABLE:
  __SCREAMING_SNAKE_CASE       :    List[Any]       =	unittest.skip("test requires Pillow"     )(__lowerCamelCase     )
 return test_case






def 	_lowerCAmelCase						(				__lowerCamelCase   :     Any     ):



 """simple docstring"""





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






def 	_lowerCAmelCase						(				__lowerCamelCase   :     Optional[Any]     ):



 """simple docstring"""





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






def 	_lowerCAmelCase						(				__lowerCamelCase   :     List[Any]     ):



 """simple docstring"""





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






def 	_lowerCAmelCase						(				__lowerCamelCase   :     str     ):



 """simple docstring"""





 def _require_spacy_model(__lowerCamelCase   :     Optional[Any]     ):
  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 	_lowerCAmelCase						(				__lowerCamelCase   :     Optional[int]     ):



 """simple docstring"""





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






def 	_lowerCAmelCase						(				__lowerCamelCase   :     Union[str, Any]     ):



 """simple docstring"""





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






def 	_lowerCAmelCase						(				__lowerCamelCase   :     Dict     ):



 """simple docstring"""





 if not _run_slow_tests or _run_slow_tests == 0:
  __SCREAMING_SNAKE_CASE       :    int       =	unittest.skip("test is slow"     )(__lowerCamelCase     )
 return test_case






def 	_lowerCAmelCase						(				__lowerCamelCase   :     Optional[Any]     ):



 """simple docstring"""





 if not _run_local_tests or _run_local_tests == 0:
  __SCREAMING_SNAKE_CASE       :    List[str]       =	unittest.skip("test is local"     )(__lowerCamelCase     )
 return test_case






def 	_lowerCAmelCase						(				__lowerCamelCase   :     Any     ):



 """simple docstring"""





 if not _run_packaged_tests or _run_packaged_tests == 0:
  __SCREAMING_SNAKE_CASE       :    str       =	unittest.skip("test is packaged"     )(__lowerCamelCase     )
 return test_case






def 	_lowerCAmelCase						(				__lowerCamelCase   :     Any     ):



 """simple docstring"""





 if not _run_remote_tests or _run_remote_tests == 0:
  __SCREAMING_SNAKE_CASE       :    Tuple       =	unittest.skip("test requires remote"     )(__lowerCamelCase     )
 return test_case






def 	_lowerCAmelCase						(				*__lowerCamelCase   :     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:
     __SCREAMING_SNAKE_CASE       :    Dict       =	decorator(__lowerCamelCase     )
    setattr(cls		,	__lowerCamelCase		,	__lowerCamelCase     )
  return cls

 return decorate

class       _SCREAMING_SNAKE_CASE	(UpperCamelCase ):
     pass






class       _SCREAMING_SNAKE_CASE	(UpperCamelCase ):
     lowerCAmelCase     :   Tuple					=			0
     lowerCAmelCase     :   List[str]					=			1
     lowerCAmelCase     :   Union[str, Any]					=			2






@contextmanager
def 	_lowerCAmelCase						(				__lowerCamelCase   :     List[str]=OfflineSimulationMode.CONNECTION_FAILS		,	__lowerCamelCase   :     str=1E-16     ):



 """simple docstring"""





 __SCREAMING_SNAKE_CASE       :    Tuple       =	requests.Session().request

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

 def raise_connection_error(__lowerCamelCase   :     List[Any]		,	__lowerCamelCase   :     Dict		,	**__lowerCamelCase   :     Optional[Any]     ):
  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 	_lowerCAmelCase						(				*__lowerCamelCase   :     Optional[int]		,	**__lowerCamelCase   :     str     ):



 """simple docstring"""





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






@contextmanager
def 	_lowerCAmelCase						(				):



 """simple docstring"""





 import gc

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






@contextmanager
def 	_lowerCAmelCase						(				):



 """simple docstring"""





 import gc

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






def 	_lowerCAmelCase						(				__lowerCamelCase   :     Union[str, Any]		,	__lowerCamelCase   :     Union[str, Any]     ):



 """simple docstring"""





 return deepcopy(__lowerCamelCase     ).integers(0		,	100		,	10     ).tolist() == deepcopy(__lowerCamelCase     ).integers(0		,	100		,	10     ).tolist()






def 	_lowerCAmelCase						(				__lowerCamelCase   :     List[str]     ):



 """simple docstring"""





 import decorator
 from requests.exceptions import HTTPError

 def _wrapper(__lowerCamelCase   :     List[str]		,	*__lowerCamelCase   :     Any		,	**__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       _SCREAMING_SNAKE_CASE	:





     def __init__(       self :							int     ,  UpperCamelCase :							Optional[int]     ,  UpperCamelCase :							Dict     ,  UpperCamelCase :							Optional[int]				)->List[Any]:
      __SCREAMING_SNAKE_CASE       :    Tuple       =	returncode
      __SCREAMING_SNAKE_CASE       :    Any       =	stdout
      __SCREAMING_SNAKE_CASE       :    int       =	stderr






async def 	_lowerCAmelCase						(				__lowerCamelCase   :     List[str]		,	__lowerCamelCase   :     Tuple     ):



 """simple docstring"""





 while True:
  __SCREAMING_SNAKE_CASE       :    Any       =	await stream.readline()
  if line:
   callback(__lowerCamelCase     )
  else:
   break






async def 	_lowerCAmelCase						(				__lowerCamelCase   :     Dict		,	__lowerCamelCase   :     int=None		,	__lowerCamelCase   :     List[Any]=None		,	__lowerCamelCase   :     str=None		,	__lowerCamelCase   :     Dict=False		,	__lowerCamelCase   :     Tuple=False     ):



 """simple docstring"""





 if echo:
  print("\nRunning: "		,	" ".join(__lowerCamelCase     )     )

 __SCREAMING_SNAKE_CASE       :    List[str]       =	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)

 __SCREAMING_SNAKE_CASE       :    Dict       =	[]
 __SCREAMING_SNAKE_CASE       :    int       =	[]

 def tee(__lowerCamelCase   :     Tuple		,	__lowerCamelCase   :     List[str]		,	__lowerCamelCase   :     List[str]		,	__lowerCamelCase   :     Union[str, Any]=""     ):
  __SCREAMING_SNAKE_CASE       :    str       =	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 	_lowerCAmelCase						(				__lowerCamelCase   :     List[str]		,	__lowerCamelCase   :     Any=None		,	__lowerCamelCase   :     Union[str, Any]=None		,	__lowerCamelCase   :     Optional[int]=180		,	__lowerCamelCase   :     Optional[int]=False		,	__lowerCamelCase   :     int=True     ):



 """simple docstring"""





 __SCREAMING_SNAKE_CASE       :    int       =	asyncio.get_event_loop()
 __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	loop.run_until_complete(
     _stream_subprocess(__lowerCamelCase		,	env=__lowerCamelCase		,	stdin=__lowerCamelCase		,	timeout=__lowerCamelCase		,	quiet=__lowerCamelCase		,	echo=__lowerCamelCase     )     )

 __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	" ".join(__lowerCamelCase     )
 if result.returncode > 0:
  __SCREAMING_SNAKE_CASE       :    str       =	"\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						(				):



 """simple docstring"""





 __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	os.environ.get("PYTEST_XDIST_WORKER"		,	"gw0"     )
 __SCREAMING_SNAKE_CASE       :    Dict       =	re.sub(r"^gw"		,	""		,	__lowerCamelCase		,	0		,	re.M     )
 return int(__lowerCamelCase     )






def 	_lowerCAmelCase						(				):



 """simple docstring"""





 __SCREAMING_SNAKE_CASE       :    Tuple       =	29500
 __SCREAMING_SNAKE_CASE       :    List[str]       =	pytest_xdist_worker_id()
 return port + uniq_delta











import unittest
from typing import Dict, List, Optional, Union

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
      import torch

if is_vision_available():
      from PIL import Image

      from transformers import BridgeTowerImageProcessor

class       _SCREAMING_SNAKE_CASE	(unittest.TestCase ):





     def __init__(       self :							Union[str, Any]     ,  UpperCamelCase :							List[Any]     ,  UpperCamelCase :							bool = True     ,  UpperCamelCase :							Dict[str, int] = None     ,  UpperCamelCase :							int = 3_2     ,  UpperCamelCase :							bool = True     ,  UpperCamelCase :							Union[int, float] = 1 / 2_5_5     ,  UpperCamelCase :							bool = True     ,  UpperCamelCase :							bool = True     ,  UpperCamelCase :							Optional[Union[float, List[float]]] = [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3]     ,  UpperCamelCase :							Optional[Union[float, List[float]]] = [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1]     ,  UpperCamelCase :							bool = True     ,  UpperCamelCase :							Dict=7     ,  UpperCamelCase :							Dict=3_0     ,  UpperCamelCase :							Tuple=4_0_0     ,  UpperCamelCase :							Union[str, Any]=3     ,  )->Optional[int]:
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	parent
      __SCREAMING_SNAKE_CASE       :    str       =	do_resize
      __SCREAMING_SNAKE_CASE       :    Optional[int]       =	size if size is not None else {"shortest_edge": 2_8_8}
      __SCREAMING_SNAKE_CASE       :    List[str]       =	size_divisor
      __SCREAMING_SNAKE_CASE       :    str       =	do_rescale
      __SCREAMING_SNAKE_CASE       :    int       =	rescale_factor
      __SCREAMING_SNAKE_CASE       :    Tuple       =	do_normalize
      __SCREAMING_SNAKE_CASE       :    List[Any]       =	do_center_crop
      __SCREAMING_SNAKE_CASE       :    List[str]       =	image_mean
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	image_std
      __SCREAMING_SNAKE_CASE       :    Optional[int]       =	do_pad
      __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	batch_size
      __SCREAMING_SNAKE_CASE       :    str       =	num_channels
      __SCREAMING_SNAKE_CASE       :    List[str]       =	min_resolution
      __SCREAMING_SNAKE_CASE       :    Tuple       =	max_resolution





     def 	__snake_case    (       self :							Optional[Any]				)->List[str]:
      return {
          "image_mean": self.image_mean,
          "image_std": self.image_std,
          "do_normalize": self.do_normalize,
          "do_resize": self.do_resize,
          "size": self.size,
          "size_divisor": self.size_divisor,
      }






     def 	__snake_case    (       self :							Optional[Any]     ,  UpperCamelCase :							Optional[int]     ,  UpperCamelCase :							Dict=False				)->Optional[Any]:
      if not batched:
       __SCREAMING_SNAKE_CASE       :    Optional[int]       =	self.size["shortest_edge"]
       __SCREAMING_SNAKE_CASE       :    List[Any]       =	image_inputs[0]
       if isinstance(UpperCamelCase     ,  Image.Image				):
        __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    List[Any]       =	image.size
       else:
        __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	image.shape[1], image.shape[2]
       __SCREAMING_SNAKE_CASE       :    Tuple       =	size / min(UpperCamelCase     ,  UpperCamelCase				)
       if h < w:
        __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    int       =	size, scale * w
       else:
        __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    List[str]       =	scale * h, size

       __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	int((1_3_3_3 / 8_0_0) * size				)
       if max(UpperCamelCase     ,  UpperCamelCase				) > max_size:
        __SCREAMING_SNAKE_CASE       :    Any       =	max_size / max(UpperCamelCase     ,  UpperCamelCase				)
        __SCREAMING_SNAKE_CASE       :    List[Any]       =	newh * scale
        __SCREAMING_SNAKE_CASE       :    Optional[int]       =	neww * scale

       __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    List[Any]       =	int(newh + 0.5				), int(neww + 0.5				)
       __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    Optional[Any]       =	(
           newh // self.size_divisor * self.size_divisor,
           neww // self.size_divisor * self.size_divisor,
       )

      else:
       __SCREAMING_SNAKE_CASE       :    Optional[int]       =	[]
       for image in image_inputs:
        __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    Optional[Any]       =	self.get_expected_values([image]				)
        expected_values.append((expected_height, expected_width)				)
       __SCREAMING_SNAKE_CASE       :    int       =	max(UpperCamelCase     ,  key=lambda UpperCamelCase				: item[0]				)[0]
       __SCREAMING_SNAKE_CASE       :    List[str]       =	max(UpperCamelCase     ,  key=lambda UpperCamelCase				: item[1]				)[1]

      return expected_height, expected_width






@require_torch
@require_vision
class       _SCREAMING_SNAKE_CASE	(UpperCamelCase			,    unittest.TestCase ):
     lowerCAmelCase					=			BridgeTowerImageProcessor if is_vision_available() else None





     def 	__snake_case    (       self :							str				)->int:
      __SCREAMING_SNAKE_CASE       :    str       =	BridgeTowerImageProcessingTester(self				)





     @property
     def 	__snake_case    (       self :							str				)->Any:
      return self.image_processor_tester.prepare_image_processor_dict()





     def 	__snake_case    (       self :							Optional[int]				)->Dict:
      __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	self.image_processing_class(**self.image_processor_dict				)
      self.assertTrue(hasattr(UpperCamelCase     ,  "image_mean"				)				)
      self.assertTrue(hasattr(UpperCamelCase     ,  "image_std"				)				)
      self.assertTrue(hasattr(UpperCamelCase     ,  "do_normalize"				)				)
      self.assertTrue(hasattr(UpperCamelCase     ,  "do_resize"				)				)
      self.assertTrue(hasattr(UpperCamelCase     ,  "size"				)				)
      self.assertTrue(hasattr(UpperCamelCase     ,  "size_divisor"				)				)





     def 	__snake_case    (       self :							Optional[int]				)->int:
      pass





     def 	__snake_case    (       self :							str				)->Union[str, Any]:
      # Initialize image processor
      __SCREAMING_SNAKE_CASE       :    Any       =	self.image_processing_class(**self.image_processor_dict				)
      # create random PIL images
      __SCREAMING_SNAKE_CASE       :    Optional[int]       =	prepare_image_inputs(self.image_processor_tester     ,  equal_resolution=UpperCamelCase				)
      for image in image_inputs:
       self.assertIsInstance(UpperCamelCase     ,  Image.Image				)

      # Test not batched input
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	image_processing(image_inputs[0]     ,  return_tensors="pt"				).pixel_values

      __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    Tuple       =	self.image_processor_tester.get_expected_values(UpperCamelCase				)
      self.assertEqual(
          encoded_images.shape     ,  (1, self.image_processor_tester.num_channels, expected_height, expected_width)     ,  )

      # Test batched
      __SCREAMING_SNAKE_CASE       :    Any       =	image_processing(UpperCamelCase     ,  return_tensors="pt"				).pixel_values

      __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	self.image_processor_tester.get_expected_values(UpperCamelCase     ,  batched=UpperCamelCase				)
      self.assertEqual(
          encoded_images.shape     ,  (
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_channels,
              expected_height,
              expected_width,
          )     ,  )





     def 	__snake_case    (       self :							List[str]				)->Optional[int]:
      # Initialize image processor
      __SCREAMING_SNAKE_CASE       :    List[Any]       =	self.image_processing_class(**self.image_processor_dict				)
      # create random numpy tensors
      __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	prepare_image_inputs(self.image_processor_tester     ,  equal_resolution=UpperCamelCase     ,  numpify=UpperCamelCase				)
      for image in image_inputs:
       self.assertIsInstance(UpperCamelCase     ,  np.ndarray				)

      # Test not batched input
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	image_processing(image_inputs[0]     ,  return_tensors="pt"				).pixel_values

      __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    Optional[int]       =	self.image_processor_tester.get_expected_values(UpperCamelCase				)
      self.assertEqual(
          encoded_images.shape     ,  (1, self.image_processor_tester.num_channels, expected_height, expected_width)     ,  )

      # Test batched
      __SCREAMING_SNAKE_CASE       :    str       =	image_processing(UpperCamelCase     ,  return_tensors="pt"				).pixel_values

      __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    List[Any]       =	self.image_processor_tester.get_expected_values(UpperCamelCase     ,  batched=UpperCamelCase				)
      self.assertEqual(
          encoded_images.shape     ,  (
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_channels,
              expected_height,
              expected_width,
          )     ,  )






     def 	__snake_case    (       self :							Optional[Any]				)->Union[str, Any]:
      # Initialize image processor
      __SCREAMING_SNAKE_CASE       :    Dict       =	self.image_processing_class(**self.image_processor_dict				)
      # create random PyTorch tensors
      __SCREAMING_SNAKE_CASE       :    List[str]       =	prepare_image_inputs(self.image_processor_tester     ,  equal_resolution=UpperCamelCase     ,  torchify=UpperCamelCase				)
      for image in image_inputs:
       self.assertIsInstance(UpperCamelCase     ,  torch.Tensor				)

      # Test not batched input
      __SCREAMING_SNAKE_CASE       :    Optional[int]       =	image_processing(image_inputs[0]     ,  return_tensors="pt"				).pixel_values

      __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    Dict       =	self.image_processor_tester.get_expected_values(UpperCamelCase				)
      self.assertEqual(
          encoded_images.shape     ,  (1, self.image_processor_tester.num_channels, expected_height, expected_width)     ,  )

      # Test batched
      __SCREAMING_SNAKE_CASE       :    str       =	image_processing(UpperCamelCase     ,  return_tensors="pt"				).pixel_values

      __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE       :    Any       =	self.image_processor_tester.get_expected_values(UpperCamelCase     ,  batched=UpperCamelCase				)
      self.assertEqual(
          encoded_images.shape     ,  (
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_channels,
              expected_height,
              expected_width,
          )     ,  )






