



'''simple docstring'''

import logging
import os
from typing import Dict, List, Optional, Union

import torch
import torch.nn as nn

from accelerate.utils.imports import (
    is_abit_bnb_available,
    is_abit_bnb_available,
    is_bnb_available,
)

from ..big_modeling import dispatch_model, init_empty_weights
from .dataclasses import BnbQuantizationConfig
from .modeling import (
    find_tied_parameters,
    get_balanced_memory,
    infer_auto_device_map,
    load_checkpoint_in_model,
    offload_weight,
    set_module_tensor_to_device,
)


if is_bnb_available():
							import bitsandbytes as bnb

from copy import deepcopy


__lowerCAmelCase									=   logging.getLogger(__name__)



def      __lowerCamelCase     (      lowerCAmelCase_						,			lowerCAmelCase_						,			lowerCAmelCase_ = None						,			lowerCAmelCase_ = None						,			lowerCAmelCase_ = None						,			lowerCAmelCase_ = None						,			lowerCAmelCase_ = None						,			lowerCAmelCase_ = False						,			)			->      Dict:
		_a     :      str        =							bnb_quantization_config.load_in_abit
		_a     :      Dict        =							bnb_quantization_config.load_in_abit

		if load_in_abit and not is_abit_bnb_available():
				raise ImportError(
				    'You have a version of `bitsandbytes` that is not compatible with 8bit quantization,'
				    ' make sure you have the latest version of `bitsandbytes` installed.'  )
		if load_in_abit and not is_abit_bnb_available():
				raise ValueError(
				    'You have a version of `bitsandbytes` that is not compatible with 4bit quantization,'
				    'make sure you have the latest version of `bitsandbytes` installed.'  )

		_a     :      str        =							[]
		# custom device map
		if isinstance(lowerCAmelCase_						,			lowerCAmelCase_  ) and len(device_map.keys()  ) > 1:
				_a     :      List[Any]        =							[key for key, value in device_map.items() if value in ['disk', 'cpu']]

		# We keep some modules such as the lm_head in their original dtype for numerical stability reasons
		if bnb_quantization_config.skip_modules is None:
				_a     :      Optional[int]        =							get_keys_to_not_convert(lowerCAmelCase_  )

		# add cpu modules to skip modules only for 4-bit modules
		if load_in_abit:
				bnb_quantization_config.skip_modules.extend(lowerCAmelCase_  )
		_a     :      Any        =							bnb_quantization_config.skip_modules

		# We add the modules we want to keep in full precision
		if bnb_quantization_config.keep_in_fpaa_modules is None:
				_a     :      List[str]        =							[]
		_a     :      Optional[Any]        =							bnb_quantization_config.keep_in_fpaa_modules
		modules_to_not_convert.extend(lowerCAmelCase_  )

		# compatibility with peft
		_a     :      Optional[Any]        =							load_in_abit
		_a     :      Dict        =							load_in_abit

		_a     :      Tuple        =							get_parameter_device(lowerCAmelCase_  )
		if model_device.type != "meta":
				# quantization of an already loaded model
				logger.warning(
				    'It is not recommended to quantize a loaded model. '
				    'The model should be instantiated under the `init_empty_weights` context manager.'  )
				_a     :      int        =							replace_with_bnb_layers(lowerCAmelCase_						,			lowerCAmelCase_						,			modules_to_not_convert=lowerCAmelCase_  )
				# convert param to the right dtype
				_a     :      Dict        =							bnb_quantization_config.torch_dtype
				for name, param in model.state_dict().items():
						if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules  ):
								param.to(torch.floataa  )
								if param.dtype != torch.floataa:
										_a     :      Any        =							name.replace('.weight'						,			''  ).replace('.bias'						,			''  )
										_a     :      str        =							getattr(lowerCAmelCase_						,			lowerCAmelCase_						,			lowerCAmelCase_  )
										if param is not None:
												param.to(torch.floataa  )
						elif torch.is_floating_point(lowerCAmelCase_  ):
								param.to(lowerCAmelCase_  )
				if model_device.type == "cuda":
						# move everything to cpu in the first place because we can't do quantization if the weights are already on cuda
						model.cuda(torch.cuda.current_device()  )
						torch.cuda.empty_cache()
				elif torch.cuda.is_available():
						model.to(torch.cuda.current_device()  )
				else:
						raise RuntimeError('No GPU found. A GPU is needed for quantization.'  )
				logger.info(
				    f"""The model device type is {model_device.type}. However, cuda is needed for quantization."""
				    'We move the model to cuda.'  )
				return model

		elif weights_location is None:
				raise RuntimeError(
				    f"""`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} """  )

		else:
				with init_empty_weights():
						_a     :      str        =							replace_with_bnb_layers(
						    lowerCAmelCase_						,			lowerCAmelCase_						,			modules_to_not_convert=lowerCAmelCase_  )

				_a     :      List[Any]        =							get_quantized_model_device_map(
				    lowerCAmelCase_						,			lowerCAmelCase_						,			lowerCAmelCase_						,			max_memory=lowerCAmelCase_						,			no_split_module_classes=lowerCAmelCase_						,			)
				if offload_state_dict is None and device_map is not None and "disk" in device_map.values():
						_a     :      Any        =							True

				_a     :      Union[str, Any]        =							any(x in list(device_map.values()  ) for x in ['cpu', 'disk']  )

				load_checkpoint_in_model(
				    lowerCAmelCase_						,			lowerCAmelCase_						,			lowerCAmelCase_						,			dtype=bnb_quantization_config.torch_dtype						,			offload_folder=lowerCAmelCase_						,			offload_state_dict=lowerCAmelCase_						,			keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules						,			offload_abit_bnb=load_in_abit and offload						,			)
				return dispatch_model(lowerCAmelCase_						,			device_map=lowerCAmelCase_						,			offload_dir=lowerCAmelCase_  )



def      __lowerCamelCase     (      lowerCAmelCase_						,			lowerCAmelCase_						,			lowerCAmelCase_=None						,			lowerCAmelCase_=None						,			lowerCAmelCase_=None  )			->      Optional[int]:
		if device_map is None:
				if torch.cuda.is_available():
						_a     :      List[Any]        =							{'': torch.cuda.current_device()}
				else:
						raise RuntimeError('No GPU found. A GPU is needed for quantization.'  )
				logger.info('The device_map was not initialized.' 'Setting device_map to `{\'\':torch.cuda.current_device()}`.'  )

		if isinstance(lowerCAmelCase_						,			lowerCAmelCase_  ):
				if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]:
						raise ValueError(
						    'If passing a string for `device_map`, please choose \'auto\', \'balanced\', \'balanced_low_0\' or '
						    '\'sequential\'.'  )

				_a     :      Union[str, Any]        =							{}
				special_dtypes.update(
				    {
				        name: bnb_quantization_config.torch_dtype
				        for name, _ in model.named_parameters()
				        if any(m in name for m in bnb_quantization_config.skip_modules  )
				    }  )
				special_dtypes.update(
				    {
				        name: torch.floataa
				        for name, _ in model.named_parameters()
				        if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules  )
				    }  )

				_a     :      int        =							{}
				_a     :      str        =							special_dtypes
				_a     :      Tuple        =							no_split_module_classes
				_a     :      Optional[Any]        =							bnb_quantization_config.target_dtype

				# get max_memory for each device.
				if device_map != "sequential":
						_a     :      Optional[Any]        =							get_balanced_memory(
						    lowerCAmelCase_						,			low_zero=(device_map == 'balanced_low_0')						,			max_memory=lowerCAmelCase_						,			**lowerCAmelCase_						,			)

				_a     :      Optional[Any]        =							max_memory
				_a     :      Any        =							infer_auto_device_map(lowerCAmelCase_						,			**lowerCAmelCase_  )

		if isinstance(lowerCAmelCase_						,			lowerCAmelCase_  ):
				# check if don't have any quantized module on the cpu
				_a     :      Tuple        =							bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules

				_a     :      Tuple        =							{
				    key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert
				}
				for device in ["cpu", "disk"]:
						if device in device_map_without_some_modules.values():
								if bnb_quantization_config.load_in_abit:
										raise ValueError(
										    '\n                        Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit\n                        the quantized model. If you want to dispatch the model on the CPU or the disk while keeping\n                        these modules in `torch_dtype`, you need to pass a custom `device_map` to\n                        `load_and_quantize_model`. Check\n                        https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk\n                        for more details.\n                        '  )
								else:
										logger.info(
										    'Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit'  )
				del device_map_without_some_modules
		return device_map



def      __lowerCamelCase     (      lowerCAmelCase_						,			lowerCAmelCase_						,			lowerCAmelCase_=None						,			lowerCAmelCase_=None  )			->      Tuple:

		if modules_to_not_convert is None:
				_a     :      Optional[int]        =							[]

		_a       ,					_a     :      Tuple        =							_replace_with_bnb_layers(
		    lowerCAmelCase_						,			lowerCAmelCase_						,			lowerCAmelCase_						,			lowerCAmelCase_  )
		if not has_been_replaced:
				logger.warning(
				    'You are loading your model in 8bit or 4bit but no linear modules were found in your model.'
				    ' this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers.'
				    ' Please double check your model architecture, or submit an issue on github if you think this is'
				    ' a bug.'  )
		return model



def      __lowerCamelCase     (      lowerCAmelCase_						,			lowerCAmelCase_						,			lowerCAmelCase_=None						,			lowerCAmelCase_=None						,			)			->      List[Any]:
		_a     :      Any        =							False
		for name, module in model.named_children():
				if current_key_name is None:
						_a     :      List[Any]        =							[]
				current_key_name.append(lowerCAmelCase_  )
				if isinstance(lowerCAmelCase_						,			nn.Linear  ) and name not in modules_to_not_convert:
						# Check if the current key is not in the `modules_to_not_convert`
						_a     :      str        =							'.'.join(lowerCAmelCase_  )
						_a     :      Any        =							True
						for key in modules_to_not_convert:
								if (
								    (key in current_key_name_str) and (key + "." in current_key_name_str)
								) or key == current_key_name_str:
										_a     :      Any        =							False
										break
						if proceed:
								# Load bnb module with empty weight and replace ``nn.Linear` module
								if bnb_quantization_config.load_in_abit:
										_a     :      Tuple        =							bnb.nn.LinearabitLt(
										    module.in_features						,			module.out_features						,			module.bias is not None						,			has_fpaa_weights=lowerCAmelCase_						,			threshold=bnb_quantization_config.llm_inta_threshold						,			)
								elif bnb_quantization_config.load_in_abit:
										_a     :      Optional[Any]        =							bnb.nn.Linearabit(
										    module.in_features						,			module.out_features						,			module.bias is not None						,			bnb_quantization_config.bnb_abit_compute_dtype						,			compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant						,			quant_type=bnb_quantization_config.bnb_abit_quant_type						,			)
								else:
										raise ValueError('load_in_8bit and load_in_4bit can\'t be both False'  )
								_a     :      Optional[Any]        =							module.weight.data
								if module.bias is not None:
										_a     :      Union[str, Any]        =							module.bias.data
								bnb_module.requires_grad_(lowerCAmelCase_  )
								setattr(lowerCAmelCase_						,			lowerCAmelCase_						,			lowerCAmelCase_  )
								_a     :      Optional[int]        =							True
				if len(list(module.children()  )  ) > 0:
						_a       ,					_a     :      Optional[int]        =							_replace_with_bnb_layers(
						    lowerCAmelCase_						,			lowerCAmelCase_						,			lowerCAmelCase_						,			lowerCAmelCase_  )
						_a     :      Any        =							has_been_replaced | _has_been_replaced
				# Remove the last key for recursion
				current_key_name.pop(-1  )
		return model, has_been_replaced



def      __lowerCamelCase     (      lowerCAmelCase_  )			->      int:
		# Create a copy of the model
		with init_empty_weights():
				_a     :      Optional[int]        =							deepcopy(lowerCAmelCase_  )  # this has 0 cost since it is done inside `init_empty_weights` context manager`

		_a     :      int        =							find_tied_parameters(lowerCAmelCase_  )
		# For compatibility with Accelerate < 0.18
		if isinstance(lowerCAmelCase_						,			lowerCAmelCase_  ):
				_a     :      str        =							sum(list(tied_params.values()  )						,			[]  ) + list(tied_params.keys()  )
		else:
				_a     :      List[str]        =							sum(lowerCAmelCase_						,			[]  )
		_a     :      Union[str, Any]        =							len(lowerCAmelCase_  ) > 0

		# Check if it is a base model
		_a     :      str        =							False
		if hasattr(lowerCAmelCase_						,			'base_model_prefix'  ):
				_a     :      str        =							not hasattr(lowerCAmelCase_						,			model.base_model_prefix  )

		# Ignore this for base models (BertModel, GPT2Model, etc.)
		if (not has_tied_params) and is_base_model:
				return []

		# otherwise they have an attached head
		_a     :      Optional[int]        =							list(model.named_children()  )
		_a     :      int        =							[list_modules[-1][0]]

		# add last module together with tied weights
		_a     :      str        =							set(lowerCAmelCase_  ) - set(lowerCAmelCase_  )
		_a     :      Optional[Any]        =							list(set(lowerCAmelCase_  )  ) + list(lowerCAmelCase_  )

		# remove ".weight" from the keys
		_a     :      List[str]        =							['.weight', '.bias']
		_a     :      Any        =							[]
		for name in list_untouched:
				for name_to_remove in names_to_remove:
						if name_to_remove in name:
								_a     :      int        =							name.replace(lowerCAmelCase_						,			''  )
				filtered_module_names.append(lowerCAmelCase_  )

		return filtered_module_names



def      __lowerCamelCase     (      lowerCAmelCase_  )			->      Optional[Any]:
		for m in model.modules():
				if isinstance(lowerCAmelCase_						,			bnb.nn.Linearabit  ):
						return True
		return False



def      __lowerCamelCase     (      lowerCAmelCase_  )			->      Optional[Any]:
		return next(parameter.parameters()  ).device



def      __lowerCamelCase     (      lowerCAmelCase_						,			lowerCAmelCase_						,			lowerCAmelCase_						,			lowerCAmelCase_						,			lowerCAmelCase_						,			lowerCAmelCase_						,			lowerCAmelCase_  )			->      List[Any]:
		# if it is not quantized, we quantize and offload the quantized weights and the SCB stats
		if fpaa_statistics is None:
				set_module_tensor_to_device(lowerCAmelCase_						,			lowerCAmelCase_						,			0						,			dtype=lowerCAmelCase_						,			value=lowerCAmelCase_  )
				_a     :      List[Any]        =							param_name
				_a     :      List[Any]        =							model
				if "." in tensor_name:
						_a     :      Tuple        =							tensor_name.split('.'  )
						for split in splits[:-1]:
								_a     :      Union[str, Any]        =							getattr(lowerCAmelCase_						,			lowerCAmelCase_  )
								if new_module is None:
										raise ValueError(f"""{module} has no attribute {split}."""  )
								_a     :      Dict        =							new_module
						_a     :      List[Any]        =							splits[-1]
				# offload weights
				_a     :      List[str]        =							False
				offload_weight(module._parameters[tensor_name]						,			lowerCAmelCase_						,			lowerCAmelCase_						,			index=lowerCAmelCase_  )
				if hasattr(module._parameters[tensor_name]						,			'SCB'  ):
						offload_weight(
						    module._parameters[tensor_name].SCB						,			param_name.replace('weight'						,			'SCB'  )						,			lowerCAmelCase_						,			index=lowerCAmelCase_						,			)
		else:
				offload_weight(lowerCAmelCase_						,			lowerCAmelCase_						,			lowerCAmelCase_						,			index=lowerCAmelCase_  )
				offload_weight(lowerCAmelCase_						,			param_name.replace('weight'						,			'SCB'  )						,			lowerCAmelCase_						,			index=lowerCAmelCase_  )

		set_module_tensor_to_device(lowerCAmelCase_						,			lowerCAmelCase_						,			'meta'						,			dtype=lowerCAmelCase_						,			value=torch.empty(*param.size()  )  )









'''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


__lowerCAmelCase									=   None
__lowerCAmelCase									=   '''<''' 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
__lowerCAmelCase									=   [
    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 	__magic_name__						:
							lowerCAmelCase       :    bool   				=					True
							lowerCAmelCase       :    Optional[str]   				=					None
							# Automatically constructed
							lowerCAmelCase       :    ClassVar[str]   				=					"PIL.Image.Image"
							lowerCAmelCase       :    ClassVar[Any]   				=					pa.struct({'bytes': pa.binary(), 'path': pa.string()}   )
							lowerCAmelCase       :    str   				=					field(default='Image'			,						init=_UpperCamelCase			,						repr=_UpperCamelCase   )







							def __call__(							self					:       Union[str, Any]		):
									return self.pa_type







							def 							__lowercase			(							self					:       Any	,_UpperCAmelCase					:       Union[str, bytes, dict, np.ndarray, "PIL.Image.Image"]		):
									if config.PIL_AVAILABLE:
											import PIL.Image
									else:
											raise ImportError('To support encoding images, please install \'Pillow\'.'		)

									if isinstance(_UpperCAmelCase	,_UpperCAmelCase		):
											_a     :      Optional[Any]        =							np.array(_UpperCAmelCase		)

									if isinstance(_UpperCAmelCase	,_UpperCAmelCase		):
											return {"path": value, "bytes": None}
									elif isinstance(_UpperCAmelCase	,_UpperCAmelCase		):
											return {"path": None, "bytes": value}
									elif isinstance(_UpperCAmelCase	,np.ndarray		):
											# convert the image array to PNG/TIFF bytes
											return encode_np_array(_UpperCAmelCase		)
									elif isinstance(_UpperCAmelCase	,PIL.Image.Image		):
											# convert the PIL image to bytes (default format is PNG/TIFF)
											return encode_pil_image(_UpperCAmelCase		)
									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 							__lowercase			(							self					:       Optional[Any]	,_UpperCAmelCase					:       dict	,_UpperCAmelCase					:       Optional[int]=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:
											_a     :      Dict        =							{}

									_a       ,					_a     :      str        =							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(_UpperCAmelCase		):
															_a     :      Any        =							PIL.Image.open(_UpperCAmelCase		)
													else:
															_a     :      List[Any]        =							path.split('::'		)[-1]
															try:
																	_a     :      str        =							string_to_dict(_UpperCAmelCase	,config.HUB_DATASETS_URL		)['repo_id']
																	_a     :      Optional[Any]        =							token_per_repo_id.get(_UpperCAmelCase		)
															except ValueError:
																	_a     :      int        =							None
															with xopen(_UpperCAmelCase	,'rb'	,use_auth_token=_UpperCAmelCase		) as f:
																	_a     :      Tuple        =							BytesIO(f.read()		)
															_a     :      Union[str, Any]        =							PIL.Image.open(bytes_		)
									else:
											_a     :      Optional[int]        =							PIL.Image.open(BytesIO(bytes_		)		)
									image.load()  # to avoid "Too many open files" errors
									return image







							def 							__lowercase			(							self					:       int		):
									from .features import Value

									return (
									    self
									    if self.decode
									    else {
									        "bytes": Value('binary'		),
									        "path": Value('string'		),
									    }
									)







							def 							__lowercase			(							self					:       str	,_UpperCAmelCase					:       Union[pa.StringArray, pa.StructArray, pa.ListArray]		):
									if pa.types.is_string(storage.type		):
											_a     :      Union[str, Any]        =							pa.array([None] * len(_UpperCAmelCase		)	,type=pa.binary()		)
											_a     :      Union[str, Any]        =							pa.StructArray.from_arrays([bytes_array, storage]	,['bytes', 'path']	,mask=storage.is_null()		)
									elif pa.types.is_binary(storage.type		):
											_a     :      List[str]        =							pa.array([None] * len(_UpperCAmelCase		)	,type=pa.string()		)
											_a     :      Any        =							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:
													_a     :      Union[str, Any]        =							storage.field('bytes'		)
											else:
													_a     :      Tuple        =							pa.array([None] * len(_UpperCAmelCase		)	,type=pa.binary()		)
											if storage.type.get_field_index('path'		) >= 0:
													_a     :      Union[str, Any]        =							storage.field('path'		)
											else:
													_a     :      Dict        =							pa.array([None] * len(_UpperCAmelCase		)	,type=pa.string()		)
											_a     :      Optional[Any]        =							pa.StructArray.from_arrays([bytes_array, path_array]	,['bytes', 'path']	,mask=storage.is_null()		)
									elif pa.types.is_list(storage.type		):
											_a     :      List[str]        =							pa.array(
											    [encode_np_array(np.array(_UpperCAmelCase		)		)['bytes'] if arr is not None else None for arr in storage.to_pylist()]	,type=pa.binary()	,)
											_a     :      int        =							pa.array([None] * len(_UpperCAmelCase		)	,type=pa.string()		)
											_a     :      Optional[Any]        =							pa.StructArray.from_arrays(
											    [bytes_array, path_array]	,['bytes', 'path']	,mask=bytes_array.is_null()		)
									return array_cast(_UpperCAmelCase	,self.pa_type		)







							def 							__lowercase			(							self					:       Dict	,_UpperCAmelCase					:       pa.StructArray		):

									@no_op_if_value_is_null
									def path_to_bytes(_UpperCAmelCase					:       Tuple		):
											with xopen(_UpperCAmelCase	,'rb'		) as f:
													_a     :      int        =							f.read()
											return bytes_

									_a     :      Any        =							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()	,)
									_a     :      Optional[Any]        =							pa.array(
									    [os.path.basename(_UpperCAmelCase		) if path is not None else None for path in storage.field('path'		).to_pylist()]	,type=pa.string()	,)
									_a     :      Dict        =							pa.StructArray.from_arrays([bytes_array, path_array]	,['bytes', 'path']	,mask=bytes_array.is_null()		)
									return array_cast(_UpperCAmelCase	,self.pa_type		)



def      __lowerCamelCase     (      )			->      List[str]:
		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()
				_a     :      Dict        =							list(set(PIL.Image.OPEN.keys()  ) & set(PIL.Image.SAVE.keys()  )  )
		return _IMAGE_COMPRESSION_FORMATS



def      __lowerCamelCase     (      lowerCAmelCase_  )			->      bytes:
		_a     :      Optional[int]        =							BytesIO()
		if image.format in list_image_compression_formats():
				_a     :      Optional[Any]        =							image.format
		else:
				_a     :      str        =							'PNG' if image.mode in ['1', 'L', 'LA', 'RGB', 'RGBA'] else 'TIFF'
		image.save(lowerCAmelCase_						,			format=lowerCAmelCase_  )
		return buffer.getvalue()



def      __lowerCamelCase     (      lowerCAmelCase_  )			->      dict:
		if hasattr(lowerCAmelCase_						,			'filename'  ) and image.filename != "":
				return {"path": image.filename, "bytes": None}
		else:
				return {"path": None, "bytes": image_to_bytes(lowerCAmelCase_  )}



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

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

		_a     :      List[Any]        =							None

		# Multi-channel array case (only np.dtype("|u1") is allowed)
		if array.shape[2:]:
				_a     :      Optional[int]        =							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:
				_a     :      Union[str, 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:
						_a     :      str        =							dtype_byteorder + dtype_kind + str(lowerCAmelCase_  )
						_a     :      List[Any]        =							np.dtype(lowerCAmelCase_  )
						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}"""  )
		_a     :      Union[str, Any]        =							PIL.Image.fromarray(array.astype(lowerCAmelCase_  )  )
		return {"path": None, "bytes": image_to_bytes(lowerCAmelCase_  )}



def      __lowerCamelCase     (      lowerCAmelCase_  )			->      List[dict]:
		if config.PIL_AVAILABLE:
				import PIL.Image
		else:
				raise ImportError('To support encoding images, please install \'Pillow\'.'  )

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




