
'''simple docstring'''
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,
    convert_to_rgb,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    OPENAI_CLIP_MEAN,
    OPENAI_CLIP_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


A__   :		Tuple 		=logging.get_logger(__name__)


if is_vision_available():
     import PIL







class  __A				( _SCREAMING_SNAKE_CASE			):
 lowerCamelCase				       =['''pixel_values''']
 def __init__(   self			:    Union[str, Any]				,   lowerCamelCase			:    bool = True				,   lowerCamelCase			:    Dict[str, int] = None				,   lowerCamelCase			:    PILImageResampling = PILImageResampling.BICUBIC				,   lowerCamelCase			:    bool = True				,   lowerCamelCase			:    Dict[str, int] = None				,   lowerCamelCase			:    bool = True				,   lowerCamelCase			:    Union[int, float] = 1 / 2_55				,   lowerCamelCase			:    bool = True				,   lowerCamelCase			:    Optional[Union[float, List[float]]] = None				,   lowerCamelCase			:    Optional[Union[float, List[float]]] = None				,   lowerCamelCase			:    bool = True				,   **lowerCamelCase			:    str				,   ):



   """simple docstring"""





   super().__init__(**lowerCamelCase       )
   __A		:     str												=		size if size is not None else {"""shortest_edge""": 2_24}
   __A		:     Tuple												=		get_size_dict(lowerCamelCase				,   default_to_square=lowerCamelCase       )
   __A		:     Optional[Any]												=		crop_size if crop_size is not None else {"""height""": 2_24, """width""": 2_24}
   __A		:     Union[str, Any]												=		get_size_dict(lowerCamelCase				,   default_to_square=lowerCamelCase				,   param_name="""crop_size"""       )

   __A		:     List[Any]												=		do_resize
   __A		:     int												=		size
   __A		:     int												=		resample
   __A		:     Dict												=		do_center_crop
   __A		:     int												=		crop_size
   __A		:     Optional[int]												=		do_rescale
   __A		:     Union[str, Any]												=		rescale_factor
   __A		:     Tuple												=		do_normalize
   __A		:     Optional[Any]												=		image_mean if image_mean is not None else OPENAI_CLIP_MEAN
   __A		:     Tuple												=		image_std if image_std is not None else OPENAI_CLIP_STD
   __A		:     int												=		do_convert_rgb
 def 		lowercase_(   self			:    Tuple				,   lowerCamelCase			:    np.ndarray				,   lowerCamelCase			:    Dict[str, int]				,   lowerCamelCase			:    PILImageResampling = PILImageResampling.BICUBIC				,   lowerCamelCase			:    Optional[Union[str, ChannelDimension]] = None				,   **lowerCamelCase			:    Dict				,   ):



   """simple docstring"""





   __A		:     Dict												=		get_size_dict(lowerCamelCase				,   default_to_square=lowerCamelCase       )
   if "shortest_edge" not in size:
     raise ValueError(f"The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}"       )
   __A		:     int												=		get_resize_output_image_size(lowerCamelCase				,   size=size["""shortest_edge"""]				,   default_to_square=lowerCamelCase       )
   return resize(lowerCamelCase				,   size=lowerCamelCase				,   resample=lowerCamelCase				,   data_format=lowerCamelCase				,   **lowerCamelCase       )
 def 		lowercase_(   self			:    Tuple				,   lowerCamelCase			:    np.ndarray				,   lowerCamelCase			:    Dict[str, int]				,   lowerCamelCase			:    Optional[Union[str, ChannelDimension]] = None				,   **lowerCamelCase			:    Union[str, Any]				,   ):



   """simple docstring"""





   __A		:     str												=		get_size_dict(lowerCamelCase       )
   if "height" not in size or "width" not in size:
     raise ValueError(f"The `size` parameter must contain the keys (height, width). Got {size.keys()}"       )
   return center_crop(lowerCamelCase				,   size=(size["""height"""], size["""width"""])				,   data_format=lowerCamelCase				,   **lowerCamelCase       )
 def 		lowercase_(   self			:    int				,   lowerCamelCase			:    np.ndarray				,   lowerCamelCase			:    Union[int, float]				,   lowerCamelCase			:    Optional[Union[str, ChannelDimension]] = None				,   **lowerCamelCase			:    int				,   ):



   """simple docstring"""





   return rescale(lowerCamelCase				,   scale=lowerCamelCase				,   data_format=lowerCamelCase				,   **lowerCamelCase       )
 def 		lowercase_(   self			:    Optional[Any]				,   lowerCamelCase			:    np.ndarray				,   lowerCamelCase			:    Union[float, List[float]]				,   lowerCamelCase			:    Union[float, List[float]]				,   lowerCamelCase			:    Optional[Union[str, ChannelDimension]] = None				,   **lowerCamelCase			:    List[Any]				,   ):



   """simple docstring"""





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






 def 		lowercase_(   self			:    List[str]				,   lowerCamelCase			:    ImageInput				,   lowerCamelCase			:    bool = None				,   lowerCamelCase			:    Dict[str, int] = None				,   lowerCamelCase			:    PILImageResampling = None				,   lowerCamelCase			:    bool = None				,   lowerCamelCase			:    int = None				,   lowerCamelCase			:    bool = None				,   lowerCamelCase			:    float = None				,   lowerCamelCase			:    bool = None				,   lowerCamelCase			:    Optional[Union[float, List[float]]] = None				,   lowerCamelCase			:    Optional[Union[float, List[float]]] = None				,   lowerCamelCase			:    bool = None				,   lowerCamelCase			:    Optional[Union[str, TensorType]] = None				,   lowerCamelCase			:    Optional[ChannelDimension] = ChannelDimension.FIRST				,   **lowerCamelCase			:    List[str]				,   ):



   """simple docstring"""





   __A		:     List[Any]												=		do_resize if do_resize is not None else self.do_resize
   __A		:     Dict												=		size if size is not None else self.size
   __A		:     List[str]												=		get_size_dict(lowerCamelCase				,   param_name="""size"""				,   default_to_square=lowerCamelCase       )
   __A		:     Optional[Any]												=		resample if resample is not None else self.resample
   __A		:     List[Any]												=		do_center_crop if do_center_crop is not None else self.do_center_crop
   __A		:     Tuple												=		crop_size if crop_size is not None else self.crop_size
   __A		:     Tuple												=		get_size_dict(lowerCamelCase				,   param_name="""crop_size"""				,   default_to_square=lowerCamelCase       )
   __A		:     Union[str, Any]												=		do_rescale if do_rescale is not None else self.do_rescale
   __A		:     Union[str, Any]												=		rescale_factor if rescale_factor is not None else self.rescale_factor
   __A		:     Tuple												=		do_normalize if do_normalize is not None else self.do_normalize
   __A		:     int												=		image_mean if image_mean is not None else self.image_mean
   __A		:     Any												=		image_std if image_std is not None else self.image_std
   __A		:     Union[str, Any]												=		do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

   __A		:     Optional[int]												=		make_list_of_images(lowerCamelCase       )

   if not valid_images(lowerCamelCase       ):
     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:
     raise ValueError("""Size must be specified if do_resize is True."""       )

   if do_center_crop and crop_size is None:
     raise ValueError("""Crop size must be specified if do_center_crop is True."""       )

   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."""       )

   # PIL RGBA images are converted to RGB
   if do_convert_rgb:
     __A		:     Dict												=		[convert_to_rgb(lowerCamelCase       ) for image in images]

   # All transformations expect numpy arrays.
   __A		:     List[str]												=		[to_numpy_array(lowerCamelCase       ) for image in images]

   if do_resize:
     __A		:     Dict												=		[self.resize(image=lowerCamelCase				,   size=lowerCamelCase				,   resample=lowerCamelCase       ) for image in images]

   if do_center_crop:
     __A		:     int												=		[self.center_crop(image=lowerCamelCase				,   size=lowerCamelCase       ) for image in images]

   if do_rescale:
     __A		:     List[str]												=		[self.rescale(image=lowerCamelCase				,   scale=lowerCamelCase       ) for image in images]

   if do_normalize:
     __A		:     Any												=		[self.normalize(image=lowerCamelCase				,   mean=lowerCamelCase				,   std=lowerCamelCase       ) for image in images]

   __A		:     Union[str, Any]												=		[to_channel_dimension_format(lowerCamelCase				,   lowerCamelCase       ) for image in images]

   __A		:     Any												=		{"""pixel_values""": images}
   return BatchFeature(data=lowerCamelCase				,   tensor_type=lowerCamelCase       )





'''simple docstring'''
import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
from ...utils import logging
from ..auto import CONFIG_MAPPING


A__   :		Any 		=logging.get_logger(__name__)

A__   :		Any 		={
    'Salesforce/instruct-blip-flan-t5': 'https://huggingface.co/Salesforce/instruct-blip-flan-t5/resolve/main/config.json',
}







class  __A				( _SCREAMING_SNAKE_CASE			):
 lowerCamelCase				       ='''instructblip_vision_model'''
 def __init__(   self			:    Tuple				,   lowerCamelCase			:    Optional[int]=14_08				,   lowerCamelCase			:    str=61_44				,   lowerCamelCase			:    List[Any]=39				,   lowerCamelCase			:    Optional[Any]=16				,   lowerCamelCase			:    Optional[int]=2_24				,   lowerCamelCase			:    Any=14				,   lowerCamelCase			:    str="gelu"				,   lowerCamelCase			:    str=1e-6				,   lowerCamelCase			:    Dict=0.0				,   lowerCamelCase			:    Dict=1e-1_0				,   lowerCamelCase			:    Optional[Any]=True				,   **lowerCamelCase			:    List[str]				,   ):



   """simple docstring"""





   super().__init__(**lowerCamelCase       )

   __A		:     int												=		hidden_size
   __A		:     List[str]												=		intermediate_size
   __A		:     Tuple												=		num_hidden_layers
   __A		:     str												=		num_attention_heads
   __A		:     str												=		patch_size
   __A		:     Dict												=		image_size
   __A		:     Any												=		initializer_range
   __A		:     int												=		attention_dropout
   __A		:     str												=		layer_norm_eps
   __A		:     Optional[Any]												=		hidden_act
   __A		:     List[str]												=		qkv_bias






 @classmethod
 def 		lowercase_(   cls			:    Union[str, Any]				,   lowerCamelCase			:    Union[str, os.PathLike]				,   **lowerCamelCase			:    str       ):



   """simple docstring"""





   cls._set_token_in_kwargs(lowerCamelCase       )

   __A							,					__A		:     int												=		cls.get_config_dict(lowerCamelCase				,   **lowerCamelCase       )

   # get the vision config dict if we are loading from InstructBlipConfig
   if config_dict.get("""model_type"""       ) == "instructblip":
     __A		:     Tuple												=		config_dict["""vision_config"""]

   if "model_type" in config_dict and hasattr(cls				,   """model_type"""       ) and config_dict["model_type"] != cls.model_type:
     logger.warning(
         f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
         f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."       )

   return cls.from_dict(lowerCamelCase				,   **lowerCamelCase       )







class  __A				( _SCREAMING_SNAKE_CASE			):
 lowerCamelCase				       ='''instructblip_qformer'''
 def __init__(   self			:    Tuple				,   lowerCamelCase			:    int=3_05_22				,   lowerCamelCase			:    Tuple=7_68				,   lowerCamelCase			:    Optional[Any]=12				,   lowerCamelCase			:    Tuple=12				,   lowerCamelCase			:    str=30_72				,   lowerCamelCase			:    int="gelu"				,   lowerCamelCase			:    Union[str, Any]=0.1				,   lowerCamelCase			:    List[str]=0.1				,   lowerCamelCase			:    int=5_12				,   lowerCamelCase			:    Tuple=0.02				,   lowerCamelCase			:    List[str]=1e-1_2				,   lowerCamelCase			:    int=0				,   lowerCamelCase			:    List[str]="absolute"				,   lowerCamelCase			:    Optional[Any]=2				,   lowerCamelCase			:    List[Any]=14_08				,   **lowerCamelCase			:    List[Any]				,   ):



   """simple docstring"""





   super().__init__(pad_token_id=lowerCamelCase				,   **lowerCamelCase       )

   __A		:     List[Any]												=		vocab_size
   __A		:     List[str]												=		hidden_size
   __A		:     str												=		num_hidden_layers
   __A		:     str												=		num_attention_heads
   __A		:     List[Any]												=		hidden_act
   __A		:     str												=		intermediate_size
   __A		:     List[Any]												=		hidden_dropout_prob
   __A		:     Tuple												=		attention_probs_dropout_prob
   __A		:     Optional[Any]												=		max_position_embeddings
   __A		:     Optional[int]												=		initializer_range
   __A		:     Any												=		layer_norm_eps
   __A		:     List[Any]												=		position_embedding_type
   __A		:     List[str]												=		cross_attention_frequency
   __A		:     Dict												=		encoder_hidden_size






 @classmethod
 def 		lowercase_(   cls			:    Any				,   lowerCamelCase			:    Union[str, os.PathLike]				,   **lowerCamelCase			:    Union[str, Any]       ):



   """simple docstring"""





   cls._set_token_in_kwargs(lowerCamelCase       )

   __A							,					__A		:     List[str]												=		cls.get_config_dict(lowerCamelCase				,   **lowerCamelCase       )

   # get the qformer config dict if we are loading from InstructBlipConfig
   if config_dict.get("""model_type"""       ) == "instructblip":
     __A		:     Optional[int]												=		config_dict["""qformer_config"""]

   if "model_type" in config_dict and hasattr(cls				,   """model_type"""       ) and config_dict["model_type"] != cls.model_type:
     logger.warning(
         f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
         f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."       )

   return cls.from_dict(lowerCamelCase				,   **lowerCamelCase       )







class  __A				( _SCREAMING_SNAKE_CASE			):
 lowerCamelCase				       ='''instructblip'''
 lowerCamelCase				       =True
 def __init__(   self			:    Any				,   lowerCamelCase			:    Optional[Any]=None				,   lowerCamelCase			:    List[str]=None				,   lowerCamelCase			:    Any=None				,   lowerCamelCase			:    Any=32				,   **lowerCamelCase			:    int       ):



   """simple docstring"""





   super().__init__(**lowerCamelCase       )

   if vision_config is None:
     __A		:     int												=		{}
     logger.info("""vision_config is None. initializing the InstructBlipVisionConfig with default values."""       )

   if qformer_config is None:
     __A		:     Dict												=		{}
     logger.info("""qformer_config is None. Initializing the InstructBlipQFormerConfig with default values."""       )

   if text_config is None:
     __A		:     Any												=		{}
     logger.info("""text_config is None. Initializing the text config with default values (`OPTConfig`)."""       )

   __A		:     List[Any]												=		InstructBlipVisionConfig(**lowerCamelCase       )
   __A		:     Union[str, Any]												=		InstructBlipQFormerConfig(**lowerCamelCase       )
   __A		:     Tuple												=		text_config["""model_type"""] if """model_type""" in text_config else """opt"""
   __A		:     List[str]												=		CONFIG_MAPPING[text_model_type](**lowerCamelCase       )

   __A		:     Optional[int]												=		self.text_config.tie_word_embeddings
   __A		:     Dict												=		self.text_config.is_encoder_decoder

   __A		:     Optional[int]												=		num_query_tokens
   __A		:     int												=		self.vision_config.hidden_size
   __A		:     str												=		self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
   __A		:     Optional[Any]												=		1.0
   __A		:     Optional[int]												=		0.02
 @classmethod
 def 		lowercase_(   cls			:    List[str]				,   lowerCamelCase			:    InstructBlipVisionConfig				,   lowerCamelCase			:    InstructBlipQFormerConfig				,   lowerCamelCase			:    PretrainedConfig				,   **lowerCamelCase			:    Optional[int]				,   ):



   """simple docstring"""





   return cls(
       vision_config=vision_config.to_dict()				,   qformer_config=qformer_config.to_dict()				,   text_config=text_config.to_dict()				,   **lowerCamelCase				,   )






 def 		lowercase_(   self			:    List[Any]       ):



   """simple docstring"""





   __A		:     Tuple												=		copy.deepcopy(self.__dict__       )
   __A		:     Optional[int]												=		self.vision_config.to_dict()
   __A		:     Optional[Any]												=		self.qformer_config.to_dict()
   __A		:     List[Any]												=		self.text_config.to_dict()
   __A		:     Optional[int]												=		self.__class__.model_type
   return output



