





import os
from typing import Optional

import fsspec
from fsspec.archive import AbstractArchiveFileSystem
from fsspec.utils import DEFAULT_BLOCK_SIZE





class UpperCAmelCase_				( _SCREAMING_SNAKE_CASE ):
  __lowerCAmelCase   :						Optional[Any]							=   """"""
  __lowerCAmelCase   :						str							=   (
      None  # protocol passed in prefix to the url. ex: "gzip", for gzip://file.txt::http://foo.bar/file.txt.gz
  )
  __lowerCAmelCase   :						str							=   None  # compression type in fsspec. ex: "gzip"
  __lowerCAmelCase   :						str							=   None  # extension of the filename to strip. ex: "".gz" to get file.txt from file.txt.gz


  def __init__(							self ,__snake_case = "" ,__snake_case = None ,__snake_case = None ,**__snake_case ):



       """simple docstring"""





       super().__init__(self ,**__snake_case )
       # always open as "rb" since fsspec can then use the TextIOWrapper to make it work for "r" mode
       A_          =       fsspec.open(
           __snake_case ,mode='''rb''' ,protocol=__snake_case ,compression=self.compression ,client_kwargs={
               '''requote_redirect_url''': False,  # see https://github.com/huggingface/datasets/pull/5459
               '''trust_env''': True,  # Enable reading proxy env variables.
               **(target_options or {}).pop('''client_kwargs''' ,{} ),  # To avoid issues if it was already passed.
           } ,**(target_options or {}) ,)
       A_          =       os.path.basename(self.file.path.split('''::''' )[0] )
       A_          =       (
           self.compressed_name[: self.compressed_name.rindex('''.''' )]
           if '''.''' in self.compressed_name
           else self.compressed_name
       )
       A_          =       None


  @classmethod
  def 						__UpperCAmelCase     (							cls ,__snake_case ):



       """simple docstring"""





       return super()._strip_protocol(__snake_case ).lstrip('''/''' )


  def 						__UpperCAmelCase     (							self ):



       """simple docstring"""





       if self.dir_cache is None:
            A_          =       {**self.file.fs.info(self.file.path ), '''name''': self.uncompressed_name}
            A_          =       {f['''name''']: f}


  def 						__UpperCAmelCase     (							self ,__snake_case ):



       """simple docstring"""





       return self.file.open().read()




  def 						__UpperCAmelCase     (							self ,__snake_case ,__snake_case = "rb" ,__snake_case=None ,__snake_case=True ,__snake_case=None ,**__snake_case ,):



       """simple docstring"""





       A_          =       self._strip_protocol(__snake_case )
       if mode != "rb":
            raise ValueError(f'Tried to read with mode {mode} on file {self.file.path} opened with mode \'rb\'' )
       return self.file.open()





class UpperCAmelCase_				( _SCREAMING_SNAKE_CASE ):
  __lowerCAmelCase   :						List[Any]							=   """bz2"""
  __lowerCAmelCase   :						List[Any]							=   """bz2"""
  __lowerCAmelCase   :						Optional[int]							=   """.bz2"""





class UpperCAmelCase_				( _SCREAMING_SNAKE_CASE ):
  __lowerCAmelCase   :						List[Any]							=   """gzip"""
  __lowerCAmelCase   :						List[Any]							=   """gzip"""
  __lowerCAmelCase   :						Dict							=   """.gz"""





class UpperCAmelCase_				( _SCREAMING_SNAKE_CASE ):
  __lowerCAmelCase   :						Optional[Any]							=   """lz4"""
  __lowerCAmelCase   :						int							=   """lz4"""
  __lowerCAmelCase   :						List[str]							=   """.lz4"""





class UpperCAmelCase_				( _SCREAMING_SNAKE_CASE ):
  __lowerCAmelCase   :						List[str]							=   """xz"""
  __lowerCAmelCase   :						str							=   """xz"""
  __lowerCAmelCase   :						Tuple							=   """.xz"""





class UpperCAmelCase_				( _SCREAMING_SNAKE_CASE ):
  __lowerCAmelCase   :						Tuple							=   """zstd"""
  __lowerCAmelCase   :						int							=   """zstd"""
  __lowerCAmelCase   :						Dict							=   """.zst"""


  def __init__(							self ,__snake_case ,__snake_case = "rb" ,__snake_case = None ,__snake_case = None ,__snake_case = DEFAULT_BLOCK_SIZE ,**__snake_case ,):



       """simple docstring"""





       super().__init__(
           fo=__snake_case ,mode=__snake_case ,target_protocol=__snake_case ,target_options=__snake_case ,block_size=__snake_case ,**__snake_case ,)
       # We need to wrap the zstd decompressor to avoid this error in fsspec==2021.7.0 and zstandard==0.15.2:
       #
       # File "/Users/user/.virtualenvs/hf-datasets/lib/python3.7/site-packages/fsspec/core.py", line 145, in open
       #     out.close = close
       # AttributeError: 'zstd.ZstdDecompressionReader' object attribute 'close' is read-only
       #
       # see https://github.com/intake/filesystem_spec/issues/725
       A_          =       self.file.__enter__





       class UpperCAmelCase_				:


         def __init__(							self ,__snake_case ):



              """simple docstring"""





              A_          =       file_


         def __enter__(							self ):



              """simple docstring"""





              self._file.__enter__()
              return self


         def __exit__(							self ,*__snake_case ,**__snake_case ):



              """simple docstring"""





              self._file.__exit__(*__snake_case ,**__snake_case )


         def __iter__(							self ):



              """simple docstring"""





              return iter(self._file )


         def 						__UpperCAmelCase     (							self ):



              """simple docstring"""





              return next(self._file )




         def __getattr__(							self ,__snake_case ):



              """simple docstring"""





              return getattr(self._file ,__snake_case )

       def fixed_enter(*__snake_case ,**__snake_case ):
            return WrappedFile(_enter(*__snake_case ,**__snake_case ) )

       A_          =       fixed_enter










from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
      import PIL


a__      :     Dict         =		logging.get_logger(__name__)





class UpperCAmelCase_				( _SCREAMING_SNAKE_CASE ):
  __lowerCAmelCase   :						Optional[int]							=   ["""pixel_values"""]


  def __init__(							self ,__snake_case = True ,__snake_case = None ,__snake_case = None ,__snake_case = PILImageResampling.BILINEAR ,__snake_case = True ,__snake_case = 1 / 2_5_5 ,__snake_case = True ,__snake_case = None ,__snake_case = None ,**__snake_case ,):



       """simple docstring"""





       super().__init__(**__snake_case )
       A_          =       size if size is not None else {'''shortest_edge''': 3_8_4}
       A_          =       get_size_dict(__snake_case ,default_to_square=__snake_case )

       A_          =       do_resize
       A_          =       size
       # Default value set here for backwards compatibility where the value in config is None
       A_          =       crop_pct if crop_pct is not None else 2_2_4 / 2_5_6
       A_          =       resample
       A_          =       do_rescale
       A_          =       rescale_factor
       A_          =       do_normalize
       A_          =       image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
       A_          =       image_std if image_std is not None else IMAGENET_STANDARD_STD


  def 						__UpperCAmelCase     (							self ,__snake_case ,__snake_case ,__snake_case ,__snake_case = PILImageResampling.BICUBIC ,__snake_case = None ,**__snake_case ,):



       """simple docstring"""





       A_          =       get_size_dict(__snake_case ,default_to_square=__snake_case )
       if "shortest_edge" not in size:
            raise ValueError(f'Size dictionary must contain \'shortest_edge\' key. Got {size.keys()}' )
       A_          =       size['''shortest_edge''']

       if shortest_edge < 3_8_4:
            # maintain same ratio, resizing shortest edge to shortest_edge/crop_pct
            A_          =       int(shortest_edge / crop_pct )
            A_          =       get_resize_output_image_size(__snake_case ,size=__snake_case ,default_to_square=__snake_case )
            A_          =       resize(image=__snake_case ,size=__snake_case ,resample=__snake_case ,data_format=__snake_case ,**__snake_case )
            # then crop to (shortest_edge, shortest_edge)
            return center_crop(image=__snake_case ,size=(shortest_edge, shortest_edge) ,data_format=__snake_case ,**__snake_case )
       else:
            # warping (no cropping) when evaluated at 384 or larger
            return resize(
                __snake_case ,size=(shortest_edge, shortest_edge) ,resample=__snake_case ,data_format=__snake_case ,**__snake_case )


  def 						__UpperCAmelCase     (							self ,__snake_case ,__snake_case ,__snake_case = None ,**__snake_case ,):



       """simple docstring"""





       return rescale(__snake_case ,scale=__snake_case ,data_format=__snake_case ,**__snake_case )


  def 						__UpperCAmelCase     (							self ,__snake_case ,__snake_case ,__snake_case ,__snake_case = None ,**__snake_case ,):



       """simple docstring"""





       return normalize(__snake_case ,mean=__snake_case ,std=__snake_case ,data_format=__snake_case ,**__snake_case )




  def 						__UpperCAmelCase     (							self ,__snake_case ,__snake_case = None ,__snake_case = None ,__snake_case = None ,__snake_case = None ,__snake_case = None ,__snake_case = None ,__snake_case = None ,__snake_case = None ,__snake_case = None ,__snake_case = None ,__snake_case = ChannelDimension.FIRST ,**__snake_case ,):



       """simple docstring"""





       A_          =       do_resize if do_resize is not None else self.do_resize
       A_          =       crop_pct if crop_pct is not None else self.crop_pct
       A_          =       resample if resample is not None else self.resample
       A_          =       do_rescale if do_rescale is not None else self.do_rescale
       A_          =       rescale_factor if rescale_factor is not None else self.rescale_factor
       A_          =       do_normalize if do_normalize is not None else self.do_normalize
       A_          =       image_mean if image_mean is not None else self.image_mean
       A_          =       image_std if image_std is not None else self.image_std

       A_          =       size if size is not None else self.size
       A_          =       get_size_dict(__snake_case ,default_to_square=__snake_case )

       A_          =       make_list_of_images(__snake_case )

       if not valid_images(__snake_case ):
            raise ValueError(
                '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
                '''torch.Tensor, tf.Tensor or jax.ndarray.''' )

       if do_resize and size is None or resample is None:
            raise ValueError('''Size and resample must be specified if do_resize is True.''' )

       if do_resize and size["shortest_edge"] < 3_8_4 and crop_pct is None:
            raise ValueError('''crop_pct must be specified if size < 384.''' )

       if do_rescale and rescale_factor is None:
            raise ValueError('''Rescale factor must be specified if do_rescale is True.''' )

       if do_normalize and (image_mean is None or image_std is None):
            raise ValueError('''Image mean and std must be specified if do_normalize is True.''' )

       # All transformations expect numpy arrays.
       A_          =       [to_numpy_array(__snake_case ) for image in images]

       if do_resize:
            A_          =       [self.resize(image=__snake_case ,size=__snake_case ,crop_pct=__snake_case ,resample=__snake_case ) for image in images]

       if do_rescale:
            A_          =       [self.rescale(image=__snake_case ,scale=__snake_case ) for image in images]

       if do_normalize:
            A_          =       [self.normalize(image=__snake_case ,mean=__snake_case ,std=__snake_case ) for image in images]

       A_          =       [to_channel_dimension_format(__snake_case ,__snake_case ) for image in images]

       A_          =       {'''pixel_values''': images}
       return BatchFeature(data=__snake_case ,tensor_type=__snake_case )



