





import importlib
import os
import platform
from pathlib import Path

from packaging import version

from .utils.logging import get_logger


UpperCAmelCase_       : str							=    get_logger(__name__)

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

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

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

UpperCAmelCase_       : 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
UpperCAmelCase_       : Optional[int]							=    {"""1""", """ON""", """YES""", """TRUE"""}
UpperCAmelCase_       : int							=    ENV_VARS_TRUE_VALUES.union({"""AUTO"""})


# Imports
UpperCAmelCase_       : Optional[Any]							=    version.parse(importlib_metadata.version("""dill"""))
UpperCAmelCase_       : Union[str, Any]							=    version.parse(importlib_metadata.version("""pandas"""))
UpperCAmelCase_       : Optional[Any]							=    version.parse(importlib_metadata.version("""pyarrow"""))

UpperCAmelCase_       : List[Any]							=    os.environ.get("""USE_TF""", """AUTO""").upper()
UpperCAmelCase_       : Union[str, Any]							=    os.environ.get("""USE_TORCH""", """AUTO""").upper()
UpperCAmelCase_       : List[Any]							=    os.environ.get("""USE_JAX""", """AUTO""").upper()

UpperCAmelCase_       : Optional[int]							=    """N/A"""
UpperCAmelCase_       : Tuple							=    False

if USE_TORCH in ENV_VARS_TRUE_AND_AUTO_VALUES and USE_TF not in ENV_VARS_TRUE_VALUES:
      UpperCAmelCase_       : Optional[Any]							=    importlib.util.find_spec("""torch""") is not None
      if TORCH_AVAILABLE:
            try:
                  UpperCAmelCase_       : List[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""")

UpperCAmelCase_       : Union[str, Any]							=    """N/A"""
UpperCAmelCase_       : Dict							=    False

if USE_TF in ENV_VARS_TRUE_AND_AUTO_VALUES and USE_TORCH not in ENV_VARS_TRUE_VALUES:
      UpperCAmelCase_       : 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:
                        UpperCAmelCase_       : Union[str, Any]							=    version.parse(importlib_metadata.version(package))
                  except importlib_metadata.PackageNotFoundError:
                        continue
                  else:
                        break
            else:
                  UpperCAmelCase_       : List[Any]							=    False
      if TF_AVAILABLE:
            if TF_VERSION.major < 2:
                  logger.info(F"""TensorFlow found but with version {TF_VERSION}. `datasets` requires version 2 minimum.""")
                  UpperCAmelCase_       : str							=    False
            else:
                  logger.info(F"""TensorFlow version {TF_VERSION} available.""")
else:
      logger.info("""Disabling Tensorflow because USE_TORCH is set""")


UpperCAmelCase_       : Any							=    """N/A"""
UpperCAmelCase_       : str							=    False

if USE_JAX in ENV_VARS_TRUE_AND_AUTO_VALUES:
      UpperCAmelCase_       : str							=    importlib.util.find_spec("""jax""") is not None and importlib.util.find_spec("""jaxlib""") is not None
      if JAX_AVAILABLE:
            try:
                  UpperCAmelCase_       : 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""")


UpperCAmelCase_       : List[str]							=    os.environ.get("""USE_BEAM""", """AUTO""").upper()
UpperCAmelCase_       : Optional[int]							=    """N/A"""
UpperCAmelCase_       : int							=    False
if USE_BEAM in ENV_VARS_TRUE_AND_AUTO_VALUES:
      try:
            UpperCAmelCase_       : str							=    version.parse(importlib_metadata.version("""apache_beam"""))
            UpperCAmelCase_       : Union[str, Any]							=    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
UpperCAmelCase_       : str							=    importlib.util.find_spec("""sqlalchemy""") is not None

# Optional tools for feature decoding
UpperCAmelCase_       : str							=    importlib.util.find_spec("""PIL""") is not None
UpperCAmelCase_       : str							=    importlib.util.find_spec("""soundfile""") is not None and version.parse(
    importlib.import_module("""soundfile""").__libsndfile_version__
) >= version.parse("""1.0.31""")
UpperCAmelCase_       : Optional[Any]							=    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
UpperCAmelCase_       : Union[str, Any]							=    importlib.util.find_spec("""rarfile""") is not None
UpperCAmelCase_       : Optional[Any]							=    importlib.util.find_spec("""zstandard""") is not None
UpperCAmelCase_       : Dict							=    importlib.util.find_spec("""lz4""") is not None
UpperCAmelCase_       : Optional[int]							=    importlib.util.find_spec("""py7zr""") is not None


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

UpperCAmelCase_       : Tuple							=    os.path.join(HF_CACHE_HOME, """datasets""")
UpperCAmelCase_       : Dict							=    Path(os.getenv("""HF_DATASETS_CACHE""", DEFAULT_HF_DATASETS_CACHE))

UpperCAmelCase_       : str							=    os.path.join(HF_CACHE_HOME, """metrics""")
UpperCAmelCase_       : Dict							=    Path(os.getenv("""HF_METRICS_CACHE""", DEFAULT_HF_METRICS_CACHE))

UpperCAmelCase_       : str							=    os.path.join(HF_CACHE_HOME, """modules""")
UpperCAmelCase_       : Dict							=    Path(os.getenv("""HF_MODULES_CACHE""", DEFAULT_HF_MODULES_CACHE))

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

UpperCAmelCase_       : Optional[Any]							=    """extracted"""
UpperCAmelCase_       : List[str]							=    os.path.join(DEFAULT_DOWNLOADED_DATASETS_PATH, EXTRACTED_DATASETS_DIR)
UpperCAmelCase_       : int							=    Path(os.getenv("""HF_DATASETS_EXTRACTED_DATASETS_PATH""", DEFAULT_EXTRACTED_DATASETS_PATH))

# Download count for the website
UpperCAmelCase_       : 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)
UpperCAmelCase_       : Optional[Any]							=    10_00

# Size of the preloaded record batch in `Dataset.__iter__`
UpperCAmelCase_       : int							=    10

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

# Max shard size in bytes (e.g. to shard parquet datasets in push_to_hub or download_and_prepare)
UpperCAmelCase_       : Tuple							=    """500MB"""

# Parquet configuration
UpperCAmelCase_       : Optional[int]							=    1_00
UpperCAmelCase_       : List[Any]							=    1_00
UpperCAmelCase_       : Optional[Any]							=    1_00

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

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

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

UpperCAmelCase_       : str							=    """datasets_modules"""

UpperCAmelCase_       : List[str]							=    2_55

# Streaming
UpperCAmelCase_       : Any							=    20
UpperCAmelCase_       : Dict							=    5

# Datasets without script
UpperCAmelCase_       : Optional[int]							=    2_00
UpperCAmelCase_       : List[Any]							=    10
UpperCAmelCase_       : List[str]							=    2_00

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





import json
import os
import tempfile

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


if is_torch_available():
      import numpy as np
      import torch

if is_vision_available():
      from PIL import Image






def 						_lowerCAmelCase    (					__lowerCamelCase :  int		,						__lowerCamelCase :  str=False		,						__lowerCamelCase :  Optional[Any]=False		,						__lowerCamelCase :  int=False  ):



 """simple docstring"""





 assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

 __SCREAMING_SNAKE_CASE							:     List[str]							=						[]
 for i in range(image_processor_tester.batch_size  ):
  if equal_resolution:
   __SCREAMING_SNAKE_CASE							:     List[Any]							=						image_processor_tester.max_resolution
  else:
   # To avoid getting image width/height 0
   __SCREAMING_SNAKE_CASE							:     Optional[int]							=						image_processor_tester.min_resolution
   if getattr(__lowerCamelCase		,						"size_divisor"		,						__lowerCamelCase  ):
    # If `size_divisor` is defined, the image needs to have width/size >= `size_divisor`
    __SCREAMING_SNAKE_CASE							:     str							=						max(image_processor_tester.size_divisor		,						__lowerCamelCase  )
   __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE							:     Tuple							=						np.random.choice(np.arange(__lowerCamelCase		,						image_processor_tester.max_resolution  )		,						2  )
  image_inputs.append(
      np.random.randint(255		,						size=(image_processor_tester.num_channels, width, height)		,						dtype=np.uinta  )  )

 if not numpify and not torchify:
  # PIL expects the channel dimension as last dimension
  __SCREAMING_SNAKE_CASE							:     Dict							=						[Image.fromarray(np.moveaxis(__lowerCamelCase		,						0		,						-1  )  ) for image in image_inputs]

 if torchify:
  __SCREAMING_SNAKE_CASE							:     Dict							=						[torch.from_numpy(__lowerCamelCase  ) for image in image_inputs]

 return image_inputs






def 						_lowerCAmelCase    (					__lowerCamelCase :  str		,						__lowerCamelCase :  List[Any]=10		,						__lowerCamelCase :  Any=10		,						__lowerCamelCase :  int=False		,						__lowerCamelCase :  List[str]=False  ):



 """simple docstring"""





 __SCREAMING_SNAKE_CASE							:     Tuple							=						[]
 for i in range(image_processor_tester.num_frames  ):
  video.append(np.random.randint(255		,						size=(image_processor_tester.num_channels, width, height)		,						dtype=np.uinta  )  )

 if not numpify and not torchify:
  # PIL expects the channel dimension as last dimension
  __SCREAMING_SNAKE_CASE							:     Optional[int]							=						[Image.fromarray(np.moveaxis(__lowerCamelCase		,						0		,						-1  )  ) for frame in video]

 if torchify:
  __SCREAMING_SNAKE_CASE							:     List[Any]							=						[torch.from_numpy(__lowerCamelCase  ) for frame in video]

 return video






def 						_lowerCAmelCase    (					__lowerCamelCase :  Any		,						__lowerCamelCase :  Dict=False		,						__lowerCamelCase :  Optional[int]=False		,						__lowerCamelCase :  Any=False  ):



 """simple docstring"""





 assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

 __SCREAMING_SNAKE_CASE							:     Dict							=						[]
 for i in range(image_processor_tester.batch_size  ):
  if equal_resolution:
   __SCREAMING_SNAKE_CASE							:     List[Any]							=						image_processor_tester.max_resolution
  else:
   __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE							:     Dict							=						np.random.choice(
       np.arange(image_processor_tester.min_resolution		,						image_processor_tester.max_resolution  )		,						2  )
   __SCREAMING_SNAKE_CASE							:     Union[str, Any]							=						prepare_video(
       image_processor_tester=__lowerCamelCase		,						width=__lowerCamelCase		,						height=__lowerCamelCase		,						numpify=__lowerCamelCase		,						torchify=__lowerCamelCase		,						)
  video_inputs.append(__lowerCamelCase  )

 return video_inputs






class    _SCREAMING_SNAKE_CASE						:
     lowerCAmelCase       =      None





     def 						__snake_case     (							self			:				Dict					)->int:
      __SCREAMING_SNAKE_CASE							:     Union[str, Any]							=						self.image_processing_class(**self.image_processor_dict					)
      __SCREAMING_SNAKE_CASE							:     str							=						json.loads(image_processor.to_json_string()					)
      for key, value in self.image_processor_dict.items():
       self.assertEqual(obj[key]  ,	UpperCamelCase					)





     def 						__snake_case     (							self			:				str					)->Optional[Any]:
      __SCREAMING_SNAKE_CASE							:     Optional[Any]							=						self.image_processing_class(**self.image_processor_dict					)

      with tempfile.TemporaryDirectory() as tmpdirname:
       __SCREAMING_SNAKE_CASE							:     Dict							=						os.path.join(UpperCamelCase  ,	"image_processor.json"					)
       image_processor_first.to_json_file(UpperCamelCase					)
       __SCREAMING_SNAKE_CASE							:     Any							=						self.image_processing_class.from_json_file(UpperCamelCase					)

      self.assertEqual(image_processor_second.to_dict()  ,	image_processor_first.to_dict()					)





     def 						__snake_case     (							self			:				Optional[int]					)->Optional[Any]:
      __SCREAMING_SNAKE_CASE							:     int							=						self.image_processing_class(**self.image_processor_dict					)

      with tempfile.TemporaryDirectory() as tmpdirname:
       __SCREAMING_SNAKE_CASE							:     Any							=						image_processor_first.save_pretrained(UpperCamelCase					)[0]
       check_json_file_has_correct_format(UpperCamelCase					)
       __SCREAMING_SNAKE_CASE							:     List[Any]							=						self.image_processing_class.from_pretrained(UpperCamelCase					)

      self.assertEqual(image_processor_second.to_dict()  ,	image_processor_first.to_dict()					)





     def 						__snake_case     (							self			:				int					)->Any:
      __SCREAMING_SNAKE_CASE							:     Any							=						self.image_processing_class()
      self.assertIsNotNone(UpperCamelCase					)






     @require_torch
     @require_vision
     def 						__snake_case     (							self			:				Any					)->List[Any]:
      if self.test_cast_dtype is not None:
       # Initialize image_processor
       __SCREAMING_SNAKE_CASE							:     Optional[Any]							=						self.image_processing_class(**self.image_processor_dict					)

       # create random PyTorch tensors
       __SCREAMING_SNAKE_CASE							:     int							=						prepare_image_inputs(self.image_processor_tester  ,	equal_resolution=UpperCamelCase  ,	torchify=UpperCamelCase					)

       __SCREAMING_SNAKE_CASE							:     Union[str, Any]							=						image_processor(UpperCamelCase  ,	return_tensors="pt"					)
       # for layoutLM compatiblity
       self.assertEqual(encoding.pixel_values.device  ,	torch.device("cpu"					)					)
       self.assertEqual(encoding.pixel_values.dtype  ,	torch.floataa					)

       __SCREAMING_SNAKE_CASE							:     int							=						image_processor(UpperCamelCase  ,	return_tensors="pt"					).to(torch.floataa					)
       self.assertEqual(encoding.pixel_values.device  ,	torch.device("cpu"					)					)
       self.assertEqual(encoding.pixel_values.dtype  ,	torch.floataa					)

       __SCREAMING_SNAKE_CASE							:     Dict							=						image_processor(UpperCamelCase  ,	return_tensors="pt"					).to("cpu"  ,	torch.bfloataa					)
       self.assertEqual(encoding.pixel_values.device  ,	torch.device("cpu"					)					)
       self.assertEqual(encoding.pixel_values.dtype  ,	torch.bfloataa					)

       with self.assertRaises(UpperCamelCase					):
        __SCREAMING_SNAKE_CASE							:     List[Any]							=						image_processor(UpperCamelCase  ,	return_tensors="pt"					).to(torch.bfloataa  ,	"cpu"					)

       # Try with text + image feature
       __SCREAMING_SNAKE_CASE							:     Any							=						image_processor(UpperCamelCase  ,	return_tensors="pt"					)
       encoding.update({"input_ids": torch.LongTensor([[1, 2, 3], [4, 5, 6]]					)}					)
       __SCREAMING_SNAKE_CASE							:     Optional[int]							=						encoding.to(torch.floataa					)

       self.assertEqual(encoding.pixel_values.device  ,	torch.device("cpu"					)					)
       self.assertEqual(encoding.pixel_values.dtype  ,	torch.floataa					)
       self.assertEqual(encoding.input_ids.dtype  ,	torch.long					)






