
"""simple docstring"""
import importlib
import os
import platform
from pathlib import Path

from packaging import version

from .utils.logging import get_logger


_a   :      List[Any]       =				get_logger(__name__)

# Datasets
_a   :      Optional[Any]       =				"""https://s3.amazonaws.com/datasets.huggingface.co/datasets/datasets"""
_a   :      Union[str, Any]       =				"""https://cdn-datasets.huggingface.co/datasets/datasets"""
_a   :      List[str]       =				"""https://raw.githubusercontent.com/huggingface/datasets/{revision}/datasets/{path}/{name}"""

# Metrics
_a   :      Tuple       =				"""https://s3.amazonaws.com/datasets.huggingface.co/datasets/metrics"""
_a   :      int       =				"""https://cdn-datasets.huggingface.co/datasets/metric"""
_a   :      List[str]       =				"""https://raw.githubusercontent.com/huggingface/datasets/{revision}/metrics/{path}/{name}"""

# Hub
_a   :      int       =				os.environ.get("""HF_ENDPOINT""", """https://huggingface.co""")
_a   :      Dict       =				HF_ENDPOINT + """/datasets/{repo_id}/resolve/{revision}/{path}"""
_a   :      Dict       =				"""main"""

_a   :      List[str]       =				version.parse(platform.python_version())

if PY_VERSION < version.parse("""3.8"""):
    import importlib_metadata
else:
    import importlib.metadata as importlib_metadata

# General environment variables accepted values for booleans
_a   :      Optional[Any]       =				{"""1""", """ON""", """YES""", """TRUE"""}
_a   :      Dict       =				ENV_VARS_TRUE_VALUES.union({"""AUTO"""})


# Imports
_a   :      str       =				version.parse(importlib_metadata.version("""dill"""))
_a   :      Tuple       =				version.parse(importlib_metadata.version("""pandas"""))
_a   :      int       =				version.parse(importlib_metadata.version("""pyarrow"""))

_a   :      Tuple       =				os.environ.get("""USE_TF""", """AUTO""").upper()
_a   :      Optional[Any]       =				os.environ.get("""USE_TORCH""", """AUTO""").upper()
_a   :      Tuple       =				os.environ.get("""USE_JAX""", """AUTO""").upper()

_a   :      int       =				"""N/A"""
_a   :      str       =				False

if USE_TORCH in ENV_VARS_TRUE_AND_AUTO_VALUES and USE_TF not in ENV_VARS_TRUE_VALUES:
    _a   :      List[str]       =				importlib.util.find_spec("""torch""") is not None
    if TORCH_AVAILABLE:
        try:
            _a   :      str       =				version.parse(importlib_metadata.version("""torch"""))
            logger.info(f'PyTorch version {TORCH_VERSION} available.')
        except importlib_metadata.PackageNotFoundError:
            pass
else:
    logger.info("""Disabling PyTorch because USE_TF is set""")

_a   :      Optional[int]       =				"""N/A"""
_a   :      str       =				False

if USE_TF in ENV_VARS_TRUE_AND_AUTO_VALUES and USE_TORCH not in ENV_VARS_TRUE_VALUES:
    _a   :      List[Any]       =				importlib.util.find_spec("""tensorflow""") is not None
    if TF_AVAILABLE:
        # For the metadata, we have to look for both tensorflow and tensorflow-cpu
        for package in [
            "tensorflow",
            "tensorflow-cpu",
            "tensorflow-gpu",
            "tf-nightly",
            "tf-nightly-cpu",
            "tf-nightly-gpu",
            "intel-tensorflow",
            "tensorflow-rocm",
            "tensorflow-macos",
        ]:
            try:
                _a   :      Optional[int]       =				version.parse(importlib_metadata.version(package))
            except importlib_metadata.PackageNotFoundError:
                continue
            else:
                break
        else:
            _a   :      int       =				False
    if TF_AVAILABLE:
        if TF_VERSION.major < 2:
            logger.info(f'TensorFlow found but with version {TF_VERSION}. `datasets` requires version 2 minimum.')
            _a   :      List[str]       =				False
        else:
            logger.info(f'TensorFlow version {TF_VERSION} available.')
else:
    logger.info("""Disabling Tensorflow because USE_TORCH is set""")


_a   :      Union[str, Any]       =				"""N/A"""
_a   :      List[Any]       =				False

if USE_JAX in ENV_VARS_TRUE_AND_AUTO_VALUES:
    _a   :      int       =				importlib.util.find_spec("""jax""") is not None and importlib.util.find_spec("""jaxlib""") is not None
    if JAX_AVAILABLE:
        try:
            _a   :      Any       =				version.parse(importlib_metadata.version("""jax"""))
            logger.info(f'JAX version {JAX_VERSION} available.')
        except importlib_metadata.PackageNotFoundError:
            pass
else:
    logger.info("""Disabling JAX because USE_JAX is set to False""")


_a   :      int       =				os.environ.get("""USE_BEAM""", """AUTO""").upper()
_a   :      str       =				"""N/A"""
_a   :      List[str]       =				False
if USE_BEAM in ENV_VARS_TRUE_AND_AUTO_VALUES:
    try:
        _a   :      List[Any]       =				version.parse(importlib_metadata.version("""apache_beam"""))
        _a   :      int       =				True
        logger.info(f'Apache Beam version {BEAM_VERSION} available.')
    except importlib_metadata.PackageNotFoundError:
        pass
else:
    logger.info("""Disabling Apache Beam because USE_BEAM is set to False""")


# Optional tools for data loading
_a   :      Union[str, Any]       =				importlib.util.find_spec("""sqlalchemy""") is not None

# Optional tools for feature decoding
_a   :      Tuple       =				importlib.util.find_spec("""PIL""") is not None
_a   :      Tuple       =				importlib.util.find_spec("""soundfile""") is not None and version.parse(
    importlib.import_module("""soundfile""").__libsndfile_version__
) >= version.parse("""1.0.31""")
_a   :      Dict       =				importlib.util.find_spec("""soundfile""") is not None and version.parse(
    importlib.import_module("""soundfile""").__libsndfile_version__
) >= version.parse("""1.1.0""")

# Optional compression tools
_a   :      Dict       =				importlib.util.find_spec("""rarfile""") is not None
_a   :      Union[str, Any]       =				importlib.util.find_spec("""zstandard""") is not None
_a   :      Tuple       =				importlib.util.find_spec("""lz4""") is not None
_a   :      str       =				importlib.util.find_spec("""py7zr""") is not None


# Cache location
_a   :      int       =				"""~/.cache"""
_a   :      Optional[Any]       =				os.getenv("""XDG_CACHE_HOME""", DEFAULT_XDG_CACHE_HOME)
_a   :      List[Any]       =				os.path.join(XDG_CACHE_HOME, """huggingface""")
_a   :      Union[str, Any]       =				os.path.expanduser(os.getenv("""HF_HOME""", DEFAULT_HF_CACHE_HOME))

_a   :      Optional[Any]       =				os.path.join(HF_CACHE_HOME, """datasets""")
_a   :      Tuple       =				Path(os.getenv("""HF_DATASETS_CACHE""", DEFAULT_HF_DATASETS_CACHE))

_a   :      List[Any]       =				os.path.join(HF_CACHE_HOME, """metrics""")
_a   :      Union[str, Any]       =				Path(os.getenv("""HF_METRICS_CACHE""", DEFAULT_HF_METRICS_CACHE))

_a   :      Optional[int]       =				os.path.join(HF_CACHE_HOME, """modules""")
_a   :      Dict       =				Path(os.getenv("""HF_MODULES_CACHE""", DEFAULT_HF_MODULES_CACHE))

_a   :      Optional[int]       =				"""downloads"""
_a   :      List[Any]       =				os.path.join(HF_DATASETS_CACHE, DOWNLOADED_DATASETS_DIR)
_a   :      List[str]       =				Path(os.getenv("""HF_DATASETS_DOWNLOADED_DATASETS_PATH""", DEFAULT_DOWNLOADED_DATASETS_PATH))

_a   :      Tuple       =				"""extracted"""
_a   :      List[str]       =				os.path.join(DEFAULT_DOWNLOADED_DATASETS_PATH, EXTRACTED_DATASETS_DIR)
_a   :      Union[str, Any]       =				Path(os.getenv("""HF_DATASETS_EXTRACTED_DATASETS_PATH""", DEFAULT_EXTRACTED_DATASETS_PATH))

# Download count for the website
_a   :      Optional[Any]       =				(
    os.environ.get("""HF_UPDATE_DOWNLOAD_COUNTS""", """AUTO""").upper() in ENV_VARS_TRUE_AND_AUTO_VALUES
)

# Batch size constants. For more info, see:
# https://github.com/apache/arrow/blob/master/docs/source/cpp/arrays.rst#size-limitations-and-recommendations)
_a   :      Optional[int]       =				1_000

# Size of the preloaded record batch in `Dataset.__iter__`
_a   :      Dict       =				10

# Pickling tables works only for small tables (<4GiB)
# For big tables, we write them on disk instead
_a   :      List[str]       =				4 << 30

# Max shard size in bytes (e.g. to shard parquet datasets in push_to_hub or download_and_prepare)
_a   :      List[Any]       =				"""500MB"""

# Parquet configuration
_a   :      Optional[Any]       =				100
_a   :      Any       =				100
_a   :      Tuple       =				100

# Offline mode
_a   :      Union[str, Any]       =				os.environ.get("""HF_DATASETS_OFFLINE""", """AUTO""").upper() in ENV_VARS_TRUE_VALUES

# In-memory
_a   :      str       =				0  # Disabled
_a   :      str       =				float(os.environ.get("""HF_DATASETS_IN_MEMORY_MAX_SIZE""", DEFAULT_IN_MEMORY_MAX_SIZE))

# File names
_a   :      List[Any]       =				"""dataset.arrow"""
_a   :      List[Any]       =				"""indices.arrow"""
_a   :      Optional[int]       =				"""state.json"""
_a   :      str       =				"""dataset_info.json"""
_a   :      Optional[Any]       =				"""dataset_infos.json"""
_a   :      List[Any]       =				"""LICENSE"""
_a   :      Union[str, Any]       =				"""metric_info.json"""
_a   :      List[Any]       =				"""dataset_dict.json"""

_a   :      str       =				"""datasets_modules"""

_a   :      List[Any]       =				255

# Streaming
_a   :      Any       =				20
_a   :      Union[str, Any]       =				5

# Datasets without script
_a   :      Union[str, Any]       =				200
_a   :      List[str]       =				10
_a   :      Dict       =				200

# Progress bars
_a   :      Dict       =				0.05  # 20 progress updates per sec


import unittest

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 ViltImageProcessor

class 						_SCREAMING_SNAKE_CASE				(  unittest.TestCase				):






		"""simple docstring"""







		def __init__(      self     :					Optional[int]	,       __SCREAMING_SNAKE_CASE     :					List[str]	,       __SCREAMING_SNAKE_CASE     :					Union[str, Any]=7	,       __SCREAMING_SNAKE_CASE     :					Dict=3	,       __SCREAMING_SNAKE_CASE     :					Any=18	,       __SCREAMING_SNAKE_CASE     :					Optional[int]=30	,       __SCREAMING_SNAKE_CASE     :					int=400	,       __SCREAMING_SNAKE_CASE     :					int=True	,       __SCREAMING_SNAKE_CASE     :					Optional[int]=None	,       __SCREAMING_SNAKE_CASE     :					Any=2	,       __SCREAMING_SNAKE_CASE     :					Any=True	,       __SCREAMING_SNAKE_CASE     :					int=[0.5, 0.5, 0.5]	,       __SCREAMING_SNAKE_CASE     :					List[str]=[0.5, 0.5, 0.5]	,       ):






					"""simple docstring"""
					_snake_case														=   size if size is not None else {"shortest_edge": 30}
					_snake_case														=   parent
					_snake_case														=   batch_size
					_snake_case														=   num_channels
					_snake_case														=   image_size
					_snake_case														=   min_resolution
					_snake_case														=   max_resolution
					_snake_case														=   do_resize
					_snake_case														=   size
					_snake_case														=   size_divisor
					_snake_case														=   do_normalize
					_snake_case														=   image_mean
					_snake_case														=   image_std



		def 					_a					(      self     :					Optional[int] ):






					"""simple docstring"""
					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 					_a					(      self     :					Any	,       __SCREAMING_SNAKE_CASE     :					List[str]	,       __SCREAMING_SNAKE_CASE     :					List[Any]=False ):






					"""simple docstring"""
					if not batched:
								_snake_case														=   self.size["shortest_edge"]
								_snake_case														=   image_inputs[0]
								if isinstance(__SCREAMING_SNAKE_CASE	,       Image.Image ):
											_snake_case							,			_snake_case														=   image.size
								else:
											_snake_case							,			_snake_case														=   image.shape[1], image.shape[2]
								_snake_case														=   size / min(__SCREAMING_SNAKE_CASE	,       __SCREAMING_SNAKE_CASE )
								if h < w:
											_snake_case							,			_snake_case														=   size, scale * w
								else:
											_snake_case							,			_snake_case														=   scale * h, size

								_snake_case														=   int((1_333 / 800) * size )
								if max(__SCREAMING_SNAKE_CASE	,       __SCREAMING_SNAKE_CASE ) > max_size:
											_snake_case														=   max_size / max(__SCREAMING_SNAKE_CASE	,       __SCREAMING_SNAKE_CASE )
											_snake_case														=   newh * scale
											_snake_case														=   neww * scale

								_snake_case							,			_snake_case														=   int(newh + 0.5 ), int(neww + 0.5 )
								_snake_case							,			_snake_case														=   (
								    newh // self.size_divisor * self.size_divisor,
								    neww // self.size_divisor * self.size_divisor,
								)

					else:
								_snake_case														=   []
								for image in image_inputs:
											_snake_case							,			_snake_case														=   self.get_expected_values([image] )
											expected_values.append((expected_height, expected_width) )
								_snake_case														=   max(__SCREAMING_SNAKE_CASE	,       key=lambda __SCREAMING_SNAKE_CASE : item[0] )[0]
								_snake_case														=   max(__SCREAMING_SNAKE_CASE	,       key=lambda __SCREAMING_SNAKE_CASE : item[1] )[1]

					return expected_height, expected_width

@require_torch
@require_vision
class 						_SCREAMING_SNAKE_CASE				(  _lowercase   ,  unittest.TestCase				):






		"""simple docstring"""







		A_    			=   ViltImageProcessor if is_vision_available() else None



		def 					_a					(      self     :					Tuple ):






					"""simple docstring"""
					_snake_case														=   ViltImageProcessingTester(self )



		@property
		def 					_a					(      self     :					List[Any] ):






					"""simple docstring"""
					return self.image_processor_tester.prepare_image_processor_dict()



		def 					_a					(      self     :					Optional[int] ):






					"""simple docstring"""
					_snake_case														=   self.image_processing_class(**self.image_processor_dict )
					self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE	,       "image_mean" ) )
					self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE	,       "image_std" ) )
					self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE	,       "do_normalize" ) )
					self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE	,       "do_resize" ) )
					self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE	,       "size" ) )
					self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE	,       "size_divisor" ) )



		def 					_a					(      self     :					Optional[Any] ):






					"""simple docstring"""
					_snake_case														=   self.image_processing_class.from_dict(self.image_processor_dict )
					self.assertEqual(image_processor.size	,       {"shortest_edge": 30} )

					_snake_case														=   self.image_processing_class.from_dict(self.image_processor_dict	,       size=42 )
					self.assertEqual(image_processor.size	,       {"shortest_edge": 42} )



		def 					_a					(      self     :					Dict ):






					"""simple docstring"""
					pass



		def 					_a					(      self     :					List[Any] ):






					"""simple docstring"""
					# Initialize image_processing
					_snake_case														=   self.image_processing_class(**self.image_processor_dict )
					# create random PIL images
					_snake_case														=   prepare_image_inputs(self.image_processor_tester	,       equal_resolution=__SCREAMING_SNAKE_CASE )
					for image in image_inputs:
								self.assertIsInstance(__SCREAMING_SNAKE_CASE	,       Image.Image )

					# Test not batched input
					_snake_case														=   image_processing(image_inputs[0]	,       return_tensors="pt" ).pixel_values

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

					# Test batched
					_snake_case														=   image_processing(__SCREAMING_SNAKE_CASE	,       return_tensors="pt" ).pixel_values

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



		def 					_a					(      self     :					List[Any] ):






					"""simple docstring"""
					# Initialize image_processing
					_snake_case														=   self.image_processing_class(**self.image_processor_dict )
					# create random numpy tensors
					_snake_case														=   prepare_image_inputs(self.image_processor_tester	,       equal_resolution=__SCREAMING_SNAKE_CASE	,       numpify=__SCREAMING_SNAKE_CASE )
					for image in image_inputs:
								self.assertIsInstance(__SCREAMING_SNAKE_CASE	,       np.ndarray )

					# Test not batched input
					_snake_case														=   image_processing(image_inputs[0]	,       return_tensors="pt" ).pixel_values

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

					# Test batched
					_snake_case														=   image_processing(__SCREAMING_SNAKE_CASE	,       return_tensors="pt" ).pixel_values

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







		def 					_a					(      self     :					Dict ):






					"""simple docstring"""
					# Initialize image_processing
					_snake_case														=   self.image_processing_class(**self.image_processor_dict )
					# create random PyTorch tensors
					_snake_case														=   prepare_image_inputs(self.image_processor_tester	,       equal_resolution=__SCREAMING_SNAKE_CASE	,       torchify=__SCREAMING_SNAKE_CASE )
					for image in image_inputs:
								self.assertIsInstance(__SCREAMING_SNAKE_CASE	,       torch.Tensor )

					# Test not batched input
					_snake_case														=   image_processing(image_inputs[0]	,       return_tensors="pt" ).pixel_values

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

					# Test batched
					_snake_case														=   image_processing(__SCREAMING_SNAKE_CASE	,       return_tensors="pt" ).pixel_values

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

