




"""simple docstring"""






import os
import sys
import warnings
from dataclasses import dataclass, field
from io import BytesIO
from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union

import numpy as np
import pyarrow as pa

from .. import config
from ..download.streaming_download_manager import xopen
from ..table import array_cast
from ..utils.file_utils import is_local_path
from ..utils.py_utils import first_non_null_value, no_op_if_value_is_null, string_to_dict


if TYPE_CHECKING:
			import PIL.Image

			from .features import FeatureType


lowercase__  		=		None
lowercase__  		=		"""<""" if sys.byteorder == """little""" else """>"""
# Origin: https://github.com/python-pillow/Pillow/blob/698951e19e19972aeed56df686868f1329981c12/src/PIL/Image.py#L3126 minus "|i1" which values are not preserved correctly when saving and loading an image
lowercase__  		=		[
    np.dtype("""|b1"""),
    np.dtype("""|u1"""),
    np.dtype("""<u2"""),
    np.dtype(""">u2"""),
    np.dtype("""<i2"""),
    np.dtype(""">i2"""),
    np.dtype("""<u4"""),
    np.dtype(""">u4"""),
    np.dtype("""<i4"""),
    np.dtype(""">i4"""),
    np.dtype("""<f4"""),
    np.dtype(""">f4"""),
    np.dtype("""<f8"""),
    np.dtype(""">f8"""),
]






@dataclass
class lowerCAmelCase__			:






			'''simple docstring'''



			lowerCamelCase__   =    True
			lowerCamelCase__   =    None
			# Automatically constructed
			lowerCamelCase__   =    "PIL.Image.Image"
			lowerCamelCase__   =    pa.struct({"""bytes""": pa.binary(), """path""": pa.string()}		)
			lowerCamelCase__   =    field(default="""Image""",			init=lowercase,			repr=lowercase		)
			def __call__(						self						):
							return self.pa_type
			def       A_					(						self						,   lowercase						):
							if config.PIL_AVAILABLE:
											import PIL.Image
							else:
											raise ImportError('To support encoding images, please install \'Pillow\'.'						)

							if isinstance(lowercase						,   lowercase						):
											_lowerCamelCase  :    Dict					=					np.array(lowercase						)

							if isinstance(lowercase						,   lowercase						):
											return {"path": value, "bytes": None}
							elif isinstance(lowercase						,   lowercase						):
											return {"path": None, "bytes": value}
							elif isinstance(lowercase						,   np.ndarray						):
											# convert the image array to PNG/TIFF bytes
											return encode_np_array(lowercase						)
							elif isinstance(lowercase						,   PIL.Image.Image						):
											# convert the PIL image to bytes (default format is PNG/TIFF)
											return encode_pil_image(lowercase						)
							elif value.get('path'						) is not None and os.path.isfile(value['path']						):
											# we set "bytes": None to not duplicate the data if they're already available locally
											return {"bytes": None, "path": value.get('path'						)}
							elif value.get('bytes'						) is not None or value.get('path'						) is not None:
											# store the image bytes, and path is used to infer the image format using the file extension
											return {"bytes": value.get('bytes'						), "path": value.get('path'						)}
							else:
											raise ValueError(
											    F'''An image sample should have one of \'path\' or \'bytes\' but they are missing or None in {value}.'''						)
			def       A_					(						self						,   lowercase						,   lowercase=None						):
							if not self.decode:
											raise RuntimeError('Decoding is disabled for this feature. Please use Image(decode=True) instead.'						)

							if config.PIL_AVAILABLE:
											import PIL.Image
							else:
											raise ImportError('To support decoding images, please install \'Pillow\'.'						)

							if token_per_repo_id is None:
											_lowerCamelCase  :    Tuple					=					{}

							_lowerCamelCase,				_lowerCamelCase  :    Optional[int]					=					value['path'], value['bytes']
							if bytes_ is None:
											if path is None:
															raise ValueError(F'''An image should have one of \'path\' or \'bytes\' but both are None in {value}.'''						)
											else:
															if is_local_path(lowercase						):
																			_lowerCamelCase  :    Any					=					PIL.Image.open(lowercase						)
															else:
																			_lowerCamelCase  :    Any					=					path.split('::'						)[-1]
																			try:
																							_lowerCamelCase  :    List[Any]					=					string_to_dict(lowercase						,   config.HUB_DATASETS_URL						)['repo_id']
																							_lowerCamelCase  :    List[str]					=					token_per_repo_id.get(lowercase						)
																			except ValueError:
																							_lowerCamelCase  :    Union[str, Any]					=					None
																			with xopen(lowercase						,   'rb'						,   use_auth_token=lowercase						) as f:
																							_lowerCamelCase  :    Dict					=					BytesIO(f.read()						)
																			_lowerCamelCase  :    List[Any]					=					PIL.Image.open(bytes_						)
							else:
											_lowerCamelCase  :    Optional[Any]					=					PIL.Image.open(BytesIO(bytes_						)						)
							image.load()  # to avoid "Too many open files" errors
							return image
			def       A_					(						self						):
							from .features import Value

							return (
							    self
							    if self.decode
							    else {
							        "bytes": Value('binary'						),
							        "path": Value('string'						),
							    }
							)
			def       A_					(						self						,   lowercase						):
							if pa.types.is_string(storage.type						):
											_lowerCamelCase  :    Union[str, Any]					=					pa.array([None] * len(lowercase						)						,   type=pa.binary()						)
											_lowerCamelCase  :    List[str]					=					pa.StructArray.from_arrays([bytes_array, storage]						,   ['bytes', 'path']						,   mask=storage.is_null()						)
							elif pa.types.is_binary(storage.type						):
											_lowerCamelCase  :    List[str]					=					pa.array([None] * len(lowercase						)						,   type=pa.string()						)
											_lowerCamelCase  :    Optional[int]					=					pa.StructArray.from_arrays([storage, path_array]						,   ['bytes', 'path']						,   mask=storage.is_null()						)
							elif pa.types.is_struct(storage.type						):
											if storage.type.get_field_index('bytes'						) >= 0:
															_lowerCamelCase  :    List[str]					=					storage.field('bytes'						)
											else:
															_lowerCamelCase  :    Tuple					=					pa.array([None] * len(lowercase						)						,   type=pa.binary()						)
											if storage.type.get_field_index('path'						) >= 0:
															_lowerCamelCase  :    Dict					=					storage.field('path'						)
											else:
															_lowerCamelCase  :    str					=					pa.array([None] * len(lowercase						)						,   type=pa.string()						)
											_lowerCamelCase  :    str					=					pa.StructArray.from_arrays([bytes_array, path_array]						,   ['bytes', 'path']						,   mask=storage.is_null()						)
							elif pa.types.is_list(storage.type						):
											_lowerCamelCase  :    List[str]					=					pa.array(
											    [encode_np_array(np.array(lowercase						)						)['bytes'] if arr is not None else None for arr in storage.to_pylist()]						,   type=pa.binary()						,   )
											_lowerCamelCase  :    Optional[Any]					=					pa.array([None] * len(lowercase						)						,   type=pa.string()						)
											_lowerCamelCase  :    Tuple					=					pa.StructArray.from_arrays(
											    [bytes_array, path_array]						,   ['bytes', 'path']						,   mask=bytes_array.is_null()						)
							return array_cast(lowercase						,   self.pa_type						)






			def       A_					(						self						,   lowercase						):

							@no_op_if_value_is_null
							def path_to_bytes(lowercase						):
											with xopen(lowercase						,   'rb'						) as f:
															_lowerCamelCase  :    Optional[int]					=					f.read()
											return bytes_

							_lowerCamelCase  :    int					=					pa.array(
							    [
							        (path_to_bytes(x['path']						) if x['bytes'] is None else x['bytes']) if x is not None else None
							        for x in storage.to_pylist()
							    ]						,   type=pa.binary()						,   )
							_lowerCamelCase  :    Union[str, Any]					=					pa.array(
							    [os.path.basename(lowercase						) if path is not None else None for path in storage.field('path'						).to_pylist()]						,   type=pa.string()						,   )
							_lowerCamelCase  :    int					=					pa.StructArray.from_arrays([bytes_array, path_array]						,   ['bytes', 'path']						,   mask=bytes_array.is_null()						)
							return array_cast(lowercase						,   self.pa_type						)







def   _snake_case    (       ):
				if config.PIL_AVAILABLE:
								import PIL.Image
				else:
								raise ImportError('To support encoding images, please install \'Pillow\'.'	)

				global _IMAGE_COMPRESSION_FORMATS
				if _IMAGE_COMPRESSION_FORMATS is None:
								PIL.Image.init()
								_lowerCamelCase  :    Tuple					=					list(set(PIL.Image.OPEN.keys()	) & set(PIL.Image.SAVE.keys()	)	)
				return _IMAGE_COMPRESSION_FORMATS







def   _snake_case    (       lowercase__	):
				_lowerCamelCase  :    Any					=					BytesIO()
				if image.format in list_image_compression_formats():
								_lowerCamelCase  :    Union[str, Any]					=					image.format
				else:
								_lowerCamelCase  :    Optional[Any]					=					'PNG' if image.mode in ['1', 'L', 'LA', 'RGB', 'RGBA'] else 'TIFF'
				image.save(lowercase__							,					format=lowercase__	)
				return buffer.getvalue()







def   _snake_case    (       lowercase__	):
				if hasattr(lowercase__							,					'filename'	) and image.filename != "":
								return {"path": image.filename, "bytes": None}
				else:
								return {"path": None, "bytes": image_to_bytes(lowercase__	)}







def   _snake_case    (       lowercase__	):
				if config.PIL_AVAILABLE:
								import PIL.Image
				else:
								raise ImportError('To support encoding images, please install \'Pillow\'.'	)

				_lowerCamelCase  :    Union[str, Any]					=					array.dtype
				_lowerCamelCase  :    int					=					dtype.byteorder if dtype.byteorder != '=' else _NATIVE_BYTEORDER
				_lowerCamelCase  :    Any					=					dtype.kind
				_lowerCamelCase  :    Dict					=					dtype.itemsize

				_lowerCamelCase  :    Any					=					None

				# Multi-channel array case (only np.dtype("|u1") is allowed)
				if array.shape[2:]:
								_lowerCamelCase  :    List[Any]					=					np.dtype('|u1'	)
								if dtype_kind not in ["u", "i"]:
												raise TypeError(
												    f'''Unsupported array dtype {dtype} for image encoding. Only {dest_dtype} is supported for multi-channel arrays.'''	)
								if dtype is not dest_dtype:
												warnings.warn(f'''Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\''''	)
    # Exact match
				elif dtype in _VALID_IMAGE_ARRAY_DTPYES:
								_lowerCamelCase  :    Any					=					dtype
				else:  # Downcast the type within the kind (np.can_cast(from_type, to_type, casting="same_kind") doesn't behave as expected, so do it manually)
								while dtype_itemsize >= 1:
												_lowerCamelCase  :    Any					=					dtype_byteorder + dtype_kind + str(lowercase__	)
												_lowerCamelCase  :    Optional[Any]					=					np.dtype(lowercase__	)
												if dest_dtype in _VALID_IMAGE_ARRAY_DTPYES:
																warnings.warn(f'''Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\''''	)
																break
												else:
																dtype_itemsize //= 2

				if dest_dtype is None:
								raise TypeError(
								    f'''Cannot convert dtype {dtype} to a valid image dtype. Valid image dtypes: {_VALID_IMAGE_ARRAY_DTPYES}'''	)
				_lowerCamelCase  :    Union[str, Any]					=					PIL.Image.fromarray(array.astype(lowercase__	)	)
				return {"path": None, "bytes": image_to_bytes(lowercase__	)}







def   _snake_case    (       lowercase__	):
				if config.PIL_AVAILABLE:
								import PIL.Image
				else:
								raise ImportError('To support encoding images, please install \'Pillow\'.'	)

				if objs:
								_lowerCamelCase,				_lowerCamelCase  :    List[str]					=					first_non_null_value(lowercase__	)
								if isinstance(lowercase__							,					lowercase__	):
												return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs]
								if isinstance(lowercase__							,					np.ndarray	):
												_lowerCamelCase  :    List[Any]					=					no_op_if_value_is_null(lowercase__	)
												return [obj_to_image_dict_func(lowercase__	) for obj in objs]
								elif isinstance(lowercase__							,					PIL.Image.Image	):
												_lowerCamelCase  :    Optional[Any]					=					no_op_if_value_is_null(lowercase__	)
												return [obj_to_image_dict_func(lowercase__	) for obj in objs]
								else:
												return objs
				else:
								return objs





"""simple docstring"""






lowercase__  		=		[
    999,
    800,
    799,
    600,
    599,
    500,
    400,
    399,
    377,
    355,
    333,
    311,
    288,
    266,
    244,
    222,
    200,
    199,
    177,
    155,
    133,
    111,
    88,
    66,
    44,
    22,
    0,
]

lowercase__  		=		[
    999,
    976,
    952,
    928,
    905,
    882,
    858,
    857,
    810,
    762,
    715,
    714,
    572,
    429,
    428,
    286,
    285,
    238,
    190,
    143,
    142,
    118,
    95,
    71,
    47,
    24,
    0,
]

lowercase__  		=		[
    999,
    988,
    977,
    966,
    955,
    944,
    933,
    922,
    911,
    900,
    899,
    879,
    859,
    840,
    820,
    800,
    799,
    766,
    733,
    700,
    699,
    650,
    600,
    599,
    500,
    499,
    400,
    399,
    350,
    300,
    299,
    266,
    233,
    200,
    199,
    179,
    159,
    140,
    120,
    100,
    99,
    88,
    77,
    66,
    55,
    44,
    33,
    22,
    11,
    0,
]

lowercase__  		=		[
    999,
    995,
    992,
    989,
    985,
    981,
    978,
    975,
    971,
    967,
    964,
    961,
    957,
    956,
    951,
    947,
    942,
    937,
    933,
    928,
    923,
    919,
    914,
    913,
    908,
    903,
    897,
    892,
    887,
    881,
    876,
    871,
    870,
    864,
    858,
    852,
    846,
    840,
    834,
    828,
    827,
    820,
    813,
    806,
    799,
    792,
    785,
    784,
    777,
    770,
    763,
    756,
    749,
    742,
    741,
    733,
    724,
    716,
    707,
    699,
    698,
    688,
    677,
    666,
    656,
    655,
    645,
    634,
    623,
    613,
    612,
    598,
    584,
    570,
    569,
    555,
    541,
    527,
    526,
    505,
    484,
    483,
    462,
    440,
    439,
    396,
    395,
    352,
    351,
    308,
    307,
    264,
    263,
    220,
    219,
    176,
    132,
    88,
    44,
    0,
]

lowercase__  		=		[
    999,
    997,
    995,
    992,
    990,
    988,
    986,
    984,
    981,
    979,
    977,
    975,
    972,
    970,
    968,
    966,
    964,
    961,
    959,
    957,
    956,
    954,
    951,
    949,
    946,
    944,
    941,
    939,
    936,
    934,
    931,
    929,
    926,
    924,
    921,
    919,
    916,
    914,
    913,
    910,
    907,
    905,
    902,
    899,
    896,
    893,
    891,
    888,
    885,
    882,
    879,
    877,
    874,
    871,
    870,
    867,
    864,
    861,
    858,
    855,
    852,
    849,
    846,
    843,
    840,
    837,
    834,
    831,
    828,
    827,
    824,
    821,
    817,
    814,
    811,
    808,
    804,
    801,
    798,
    795,
    791,
    788,
    785,
    784,
    780,
    777,
    774,
    770,
    766,
    763,
    760,
    756,
    752,
    749,
    746,
    742,
    741,
    737,
    733,
    730,
    726,
    722,
    718,
    714,
    710,
    707,
    703,
    699,
    698,
    694,
    690,
    685,
    681,
    677,
    673,
    669,
    664,
    660,
    656,
    655,
    650,
    646,
    641,
    636,
    632,
    627,
    622,
    618,
    613,
    612,
    607,
    602,
    596,
    591,
    586,
    580,
    575,
    570,
    569,
    563,
    557,
    551,
    545,
    539,
    533,
    527,
    526,
    519,
    512,
    505,
    498,
    491,
    484,
    483,
    474,
    466,
    457,
    449,
    440,
    439,
    428,
    418,
    407,
    396,
    395,
    381,
    366,
    352,
    351,
    330,
    308,
    307,
    286,
    264,
    263,
    242,
    220,
    219,
    176,
    175,
    132,
    131,
    88,
    44,
    0,
]

lowercase__  		=		[
    999,
    991,
    982,
    974,
    966,
    958,
    950,
    941,
    933,
    925,
    916,
    908,
    900,
    899,
    874,
    850,
    825,
    800,
    799,
    700,
    600,
    500,
    400,
    300,
    200,
    100,
    0,
]

lowercase__  		=		[
    999,
    992,
    985,
    978,
    971,
    964,
    957,
    949,
    942,
    935,
    928,
    921,
    914,
    907,
    900,
    899,
    879,
    859,
    840,
    820,
    800,
    799,
    766,
    733,
    700,
    699,
    650,
    600,
    599,
    500,
    499,
    400,
    399,
    300,
    299,
    200,
    199,
    100,
    99,
    0,
]

lowercase__  		=		[
    999,
    996,
    992,
    989,
    985,
    982,
    979,
    975,
    972,
    968,
    965,
    961,
    958,
    955,
    951,
    948,
    944,
    941,
    938,
    934,
    931,
    927,
    924,
    920,
    917,
    914,
    910,
    907,
    903,
    900,
    899,
    891,
    884,
    876,
    869,
    861,
    853,
    846,
    838,
    830,
    823,
    815,
    808,
    800,
    799,
    788,
    777,
    766,
    755,
    744,
    733,
    722,
    711,
    700,
    699,
    688,
    677,
    666,
    655,
    644,
    633,
    622,
    611,
    600,
    599,
    585,
    571,
    557,
    542,
    528,
    514,
    500,
    499,
    485,
    471,
    457,
    442,
    428,
    414,
    400,
    399,
    379,
    359,
    340,
    320,
    300,
    299,
    279,
    259,
    240,
    220,
    200,
    199,
    166,
    133,
    100,
    99,
    66,
    33,
    0,
]