
from typing import List, Optional, Union

import numpy as np
import PIL.Image

from ...image_processing_utils import BaseImageProcessor, BatchFeature
from ...image_transforms import rescale, resize, to_channel_dimension_format
from ...image_utils import (
    ChannelDimension,
    PILImageResampling,
    get_image_size,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


lowerCamelCase  =logging.get_logger(__name__)




class 					_lowerCamelCase			(   UpperCamelCase_			):





     """simple docstring"""







     SCREAMING_SNAKE_CASE_		 =	['''pixel_values''']






     def __init__(				self    ,    __SCREAMING_SNAKE_CASE = True    ,    __SCREAMING_SNAKE_CASE = 3_2    ,    __SCREAMING_SNAKE_CASE=PILImageResampling.BILINEAR    ,    __SCREAMING_SNAKE_CASE = True    ,    **__SCREAMING_SNAKE_CASE    ,    )	-> None:




           """simple docstring"""







           UpperCamelCase__     : Dict											=					do_resize
           UpperCamelCase__     : Tuple											=					do_rescale
           UpperCamelCase__     : Dict											=					size_divisor
           UpperCamelCase__     : str											=					resample
           super().__init__(**__SCREAMING_SNAKE_CASE	)






     def  __SCREAMING_SNAKE_CASE      (				self    ,    __SCREAMING_SNAKE_CASE    ,    __SCREAMING_SNAKE_CASE    ,    __SCREAMING_SNAKE_CASE    ,    __SCREAMING_SNAKE_CASE = None    ,    **__SCREAMING_SNAKE_CASE	)	-> np.ndarray:




           """simple docstring"""







           UpperCamelCase__					,UpperCamelCase__     : Optional[Any]											=					get_image_size(__SCREAMING_SNAKE_CASE	)
           # Rounds the height and width down to the closest multiple of size_divisor
           UpperCamelCase__     : List[Any]											=					height // size_divisor * size_divisor
           UpperCamelCase__     : Dict											=					width // size_divisor * size_divisor
           UpperCamelCase__     : str											=					resize(__SCREAMING_SNAKE_CASE    ,    (new_h, new_w)    ,    resample=__SCREAMING_SNAKE_CASE    ,    data_format=__SCREAMING_SNAKE_CASE    ,    **__SCREAMING_SNAKE_CASE	)
           return image






     def  __SCREAMING_SNAKE_CASE      (				self    ,    __SCREAMING_SNAKE_CASE    ,    __SCREAMING_SNAKE_CASE    ,    __SCREAMING_SNAKE_CASE = None    ,    **__SCREAMING_SNAKE_CASE	)	-> np.ndarray:




           """simple docstring"""







           return rescale(image=__SCREAMING_SNAKE_CASE    ,    scale=__SCREAMING_SNAKE_CASE    ,    data_format=__SCREAMING_SNAKE_CASE    ,    **__SCREAMING_SNAKE_CASE	)






     def  __SCREAMING_SNAKE_CASE      (				self    ,    __SCREAMING_SNAKE_CASE    ,    __SCREAMING_SNAKE_CASE = None    ,    __SCREAMING_SNAKE_CASE = None    ,    __SCREAMING_SNAKE_CASE=None    ,    __SCREAMING_SNAKE_CASE = None    ,    __SCREAMING_SNAKE_CASE = None    ,    __SCREAMING_SNAKE_CASE = ChannelDimension.FIRST    ,    **__SCREAMING_SNAKE_CASE    ,    )	-> BatchFeature:




           """simple docstring"""







           UpperCamelCase__     : Dict											=					do_resize if do_resize is not None else self.do_resize
           UpperCamelCase__     : List[Any]											=					do_rescale if do_rescale is not None else self.do_rescale
           UpperCamelCase__     : Union[str, Any]											=					size_divisor if size_divisor is not None else self.size_divisor
           UpperCamelCase__     : List[str]											=					resample if resample is not None else self.resample

           if do_resize and size_divisor is None:
                 raise ValueError('''size_divisor is required for resizing'''	)

           UpperCamelCase__     : List[Any]											=					make_list_of_images(__SCREAMING_SNAKE_CASE	)

           if not valid_images(__SCREAMING_SNAKE_CASE	):
                 raise ValueError('''Invalid image(s)'''	)

           # All transformations expect numpy arrays.
           UpperCamelCase__     : Dict											=					[to_numpy_array(__SCREAMING_SNAKE_CASE	) for img in images]

           if do_resize:
                 UpperCamelCase__     : Optional[int]											=					[self.resize(__SCREAMING_SNAKE_CASE    ,    size_divisor=__SCREAMING_SNAKE_CASE    ,    resample=__SCREAMING_SNAKE_CASE	) for image in images]

           if do_rescale:
                 UpperCamelCase__     : Union[str, Any]											=					[self.rescale(__SCREAMING_SNAKE_CASE    ,    scale=1 / 2_5_5	) for image in images]

           UpperCamelCase__     : List[str]											=					[to_channel_dimension_format(__SCREAMING_SNAKE_CASE    ,    __SCREAMING_SNAKE_CASE	) for image in images]

           UpperCamelCase__     : Optional[Any]											=					{'''pixel_values''': images}
           return BatchFeature(data=__SCREAMING_SNAKE_CASE    ,    tensor_type=__SCREAMING_SNAKE_CASE	)




from typing import List, Union

from ..utils import (
    add_end_docstrings,
    is_tf_available,
    is_torch_available,
    is_vision_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
    from PIL import Image

    from ..image_utils import load_image

if is_tf_available():
    from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_VISION_2_SEQ_MAPPING

if is_torch_available():
    import torch

    from ..models.auto.modeling_auto import MODEL_FOR_VISION_2_SEQ_MAPPING

lowerCamelCase  =logging.get_logger(__name__)




@add_end_docstrings(UpperCamelCase_			)
class 					_lowerCamelCase			(   UpperCamelCase_			):





     """simple docstring"""







     def __init__(				self    ,    *__SCREAMING_SNAKE_CASE    ,    **__SCREAMING_SNAKE_CASE	)	-> Dict:




           """simple docstring"""







           super().__init__(*__SCREAMING_SNAKE_CASE    ,    **__SCREAMING_SNAKE_CASE	)
           requires_backends(self    ,    '''vision'''	)
           self.check_model_type(
               TF_MODEL_FOR_VISION_2_SEQ_MAPPING if self.framework == '''tf''' else MODEL_FOR_VISION_2_SEQ_MAPPING	)






     def  __SCREAMING_SNAKE_CASE      (				self    ,    __SCREAMING_SNAKE_CASE=None    ,    __SCREAMING_SNAKE_CASE=None    ,    __SCREAMING_SNAKE_CASE=None	)	-> List[Any]:




           """simple docstring"""







           UpperCamelCase__     : Tuple											=					{}
           UpperCamelCase__     : int											=					{}

           if prompt is not None:
                 UpperCamelCase__     : int											=					prompt

           if generate_kwargs is not None:
                 UpperCamelCase__     : int											=					generate_kwargs
           if max_new_tokens is not None:
                 if "generate_kwargs" not in forward_kwargs:
                       UpperCamelCase__     : Union[str, Any]											=					{}
                 if "max_new_tokens" in forward_kwargs["generate_kwargs"]:
                       raise ValueError(
                           '''\'max_new_tokens\' is defined twice, once in \'generate_kwargs\' and once as a direct parameter,'''
                           ''' please use only one'''	)
                 UpperCamelCase__     : Dict											=					max_new_tokens
           return preprocess_params, forward_kwargs, {}






     def __call__(				self    ,    __SCREAMING_SNAKE_CASE    ,    **__SCREAMING_SNAKE_CASE	)	-> List[str]:




           """simple docstring"""







           return super().__call__(__SCREAMING_SNAKE_CASE    ,    **__SCREAMING_SNAKE_CASE	)






     def  __SCREAMING_SNAKE_CASE      (				self    ,    __SCREAMING_SNAKE_CASE    ,    __SCREAMING_SNAKE_CASE=None	)	-> List[Any]:




           """simple docstring"""







           UpperCamelCase__     : List[Any]											=					load_image(__SCREAMING_SNAKE_CASE	)

           if prompt is not None:
                 if not isinstance(__SCREAMING_SNAKE_CASE    ,    __SCREAMING_SNAKE_CASE	):
                       raise ValueError(
                           F'''Received an invalid text input, got - {type(__SCREAMING_SNAKE_CASE	)} - but expected a single string. '''
                           '''Note also that one single text can be provided for conditional image to text generation.'''	)

                 UpperCamelCase__     : Optional[int]											=					self.model.config.model_type

                 if model_type == "git":
                       UpperCamelCase__     : Optional[int]											=					self.image_processor(images=__SCREAMING_SNAKE_CASE    ,    return_tensors=self.framework	)
                       UpperCamelCase__     : str											=					self.tokenizer(text=__SCREAMING_SNAKE_CASE    ,    add_special_tokens=__SCREAMING_SNAKE_CASE	).input_ids
                       UpperCamelCase__     : Dict											=					[self.tokenizer.cls_token_id] + input_ids
                       UpperCamelCase__     : int											=					torch.tensor(__SCREAMING_SNAKE_CASE	).unsqueeze(0	)
                       model_inputs.update({'''input_ids''': input_ids}	)

                 elif model_type == "pix2struct":
                       UpperCamelCase__     : Tuple											=					self.image_processor(images=__SCREAMING_SNAKE_CASE    ,    header_text=__SCREAMING_SNAKE_CASE    ,    return_tensors=self.framework	)

                 elif model_type != "vision-encoder-decoder":
                       # vision-encoder-decoder does not support conditional generation
                       UpperCamelCase__     : int											=					self.image_processor(images=__SCREAMING_SNAKE_CASE    ,    return_tensors=self.framework	)
                       UpperCamelCase__     : int											=					self.tokenizer(__SCREAMING_SNAKE_CASE    ,    return_tensors=self.framework	)
                       model_inputs.update(__SCREAMING_SNAKE_CASE	)

                 else:
                       raise ValueError(F'''Model type {model_type} does not support conditional text generation'''	)

           else:
                 UpperCamelCase__     : str											=					self.image_processor(images=__SCREAMING_SNAKE_CASE    ,    return_tensors=self.framework	)

           if self.model.config.model_type == "git" and prompt is None:
                 UpperCamelCase__     : Optional[Any]											=					None

           return model_inputs






     def  __SCREAMING_SNAKE_CASE      (				self    ,    __SCREAMING_SNAKE_CASE    ,    __SCREAMING_SNAKE_CASE=None	)	-> Optional[Any]:




           """simple docstring"""







           if (
               "input_ids" in model_inputs
               and isinstance(model_inputs['''input_ids''']    ,    __SCREAMING_SNAKE_CASE	)
               and all(x is None for x in model_inputs['''input_ids''']	)
           ):
                 UpperCamelCase__     : Union[str, Any]											=					None

           if generate_kwargs is None:
                 UpperCamelCase__     : Optional[Any]											=					{}
           # FIXME: We need to pop here due to a difference in how `generation.py` and `generation.tf_utils.py`
           #  parse inputs. In the Tensorflow version, `generate` raises an error if we don't use `input_ids` whereas
           #  the PyTorch version matches it with `self.model.main_input_name` or `self.model.encoder.main_input_name`
           #  in the `_prepare_model_inputs` method.
           UpperCamelCase__     : Any											=					model_inputs.pop(self.model.main_input_name	)
           UpperCamelCase__     : Any											=					self.model.generate(__SCREAMING_SNAKE_CASE    ,    **__SCREAMING_SNAKE_CASE    ,    **__SCREAMING_SNAKE_CASE	)
           return model_outputs






     def  __SCREAMING_SNAKE_CASE      (				self    ,    __SCREAMING_SNAKE_CASE	)	-> int:




           """simple docstring"""







           UpperCamelCase__     : Union[str, Any]											=					[]
           for output_ids in model_outputs:
                 UpperCamelCase__     : str											=					{
                     '''generated_text''': self.tokenizer.decode(
                         __SCREAMING_SNAKE_CASE    ,    skip_special_tokens=__SCREAMING_SNAKE_CASE    ,    )
                 }
                 records.append(__SCREAMING_SNAKE_CASE	)
           return records


