



from typing import List, Optional, Union

import numpy as np
import tensorflow as tf

from .utils import logging


__snake_case						:List[str]						=					logging.get_logger(__name__)





def 					__snake_case     (      _UpperCAmelCase    ):
    if isinstance(_UpperCAmelCase       ,			np.ndarray    ):
        return list(tensor.shape    )

    __a							=    tf.shape(_UpperCAmelCase    )

    if tensor.shape == tf.TensorShape(_UpperCAmelCase    ):
        return dynamic

    __a							=    tensor.shape.as_list()

    return [dynamic[i] if s is None else s for i, s in enumerate(_UpperCAmelCase    )]





def 					__snake_case     (      _UpperCAmelCase       ,			_UpperCAmelCase = None       ,			_UpperCAmelCase = None    ):
    return tf.nn.softmax(logits=logits + 1E-9       ,			axis=_UpperCAmelCase       ,			name=_UpperCAmelCase    )





def 					__snake_case     (      _UpperCAmelCase       ,			_UpperCAmelCase       ,			_UpperCAmelCase       ,			_UpperCAmelCase=1E-5       ,			_UpperCAmelCase=-1    ):
    # This is a very simplified functional layernorm, designed to duplicate
    # the functionality of PyTorch nn.functional.layer_norm when this is needed to port
    # models in Transformers.

    if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(_UpperCAmelCase       ,			_UpperCAmelCase    ):
        raise NotImplementedError('''Only 1D weight and bias tensors are supported for now, with only a single axis.'''    )

    # Get mean and variance on the axis to be normalized
    __a	,       __a							=    tf.nn.moments(_UpperCAmelCase       ,			axes=[axis]       ,			keepdims=_UpperCAmelCase    )

    if axis != -1:
        # Reshape scale and weight to have the same rank as inputs, but with 1 dimensions
        # on every dimension except axis
        __a							=    [1] * inputs.shape.rank
        __a							=    shape_list(_UpperCAmelCase    )[axis]
        __a							=    tf.reshape(_UpperCAmelCase       ,			_UpperCAmelCase    )
        __a							=    tf.reshape(_UpperCAmelCase       ,			_UpperCAmelCase    )

    # Compute layer normalization using the batch_normalization
    # function.
    __a							=    tf.nn.batch_normalization(
        _UpperCAmelCase       ,			_UpperCAmelCase       ,			_UpperCAmelCase       ,			offset=_UpperCAmelCase       ,			scale=_UpperCAmelCase       ,			variance_epsilon=_UpperCAmelCase       ,			)
    return outputs





def 					__snake_case     (      _UpperCAmelCase       ,			_UpperCAmelCase=0       ,			_UpperCAmelCase=-1    ):
    # Replicates the behavior of torch.flatten in TF

    # If end_dim or start_dim is negative, count them from the end
    if end_dim < 0:
        end_dim += input.shape.rank
    if start_dim < 0:
        start_dim += input.shape.rank

    if start_dim == end_dim:
        return input

    __a							=    tf.shape(_UpperCAmelCase    )
    __a							=    tf.math.reduce_prod(in_shape[start_dim : end_dim + 1]    )
    __a							=    tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]]       ,			axis=0    )
    return tf.reshape(_UpperCAmelCase       ,			_UpperCAmelCase    )





def 					__snake_case     (      _UpperCAmelCase    ):
    if not isinstance(_UpperCAmelCase       ,			tf.Tensor    ):
        __a							=    tf.convert_to_tensor(_UpperCAmelCase    )  # Catches stray NumPy inputs
    if encoder_attention_mask.shape.rank == 3:
        __a							=    encoder_attention_mask[:, None, :, :]
    if encoder_attention_mask.shape.rank == 2:
        __a							=    encoder_attention_mask[:, None, None, :]
    # T5 has a mask that can compare sequence ids, we can simulate this here with this transposition
    # Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow
    # /transformer/transformer_layers.py#L270
    # encoder_extended_attention_mask = (encoder_extended_attention_mask ==
    # encoder_extended_attention_mask.transpose(-1, -2))
    __a							=    (
        tf.cast(1       ,			encoder_attention_mask.dtype    ) - encoder_extended_attention_mask
    ) * encoder_extended_attention_mask.dtype.min

    return encoder_extended_attention_mask





def 					__snake_case     (      _UpperCAmelCase       ,			_UpperCAmelCase       ,			_UpperCAmelCase = "input_ids"    ):
    tf.debugging.assert_less(
        _UpperCAmelCase       ,			tf.cast(_UpperCAmelCase       ,			dtype=tensor.dtype    )       ,			message=(
            f'The maximum value of {tensor_name} ({tf.math.reduce_max(_UpperCAmelCase    )}) must be smaller than the embedding '
            f'layer\'s input dimension ({embed_dim}). The likely cause is some problem at tokenization time.'
        )       ,			)





def 					__snake_case     (      _UpperCAmelCase       ,			_UpperCAmelCase       ,			_UpperCAmelCase    ):
    __a							=    64512
    # Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT`
    # because in that case even chunking the array would not make the saving
    # possible.
    __a							=    [x for x in data if len(_UpperCAmelCase    ) > HDF5_OBJECT_HEADER_LIMIT]

    # Expecting this to never be true.
    if bad_attributes:
        raise RuntimeError(
            '''The following attributes cannot be saved to HDF5 file because '''
            f'they are larger than {HDF5_OBJECT_HEADER_LIMIT} '
            f'bytes: {bad_attributes}'    )

    __a							=    np.asarray(_UpperCAmelCase    )

    __a							=    1
    __a							=    np.array_split(_UpperCAmelCase       ,			_UpperCAmelCase    )

    # This will never loop forever thanks to the test above.
    while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data    ):
        num_chunks += 1
        __a							=    np.array_split(_UpperCAmelCase       ,			_UpperCAmelCase    )

    if num_chunks > 1:
        for chunk_id, chunk_data in enumerate(_UpperCAmelCase    ):
            __a							=    chunk_data
    else:
        __a							=    data





def 					__snake_case     (      _UpperCAmelCase       ,			_UpperCAmelCase    ):
    if name in group.attrs:
        __a							=    [n.decode('''utf8'''    ) if hasattr(_UpperCAmelCase       ,			'''decode'''    ) else n for n in group.attrs[name]]
    else:
        __a							=    []
        __a							=    0
        while "%s%d" % (name, chunk_id) in group.attrs:
            data.extend(
                [n.decode('''utf8'''    ) if hasattr(_UpperCAmelCase       ,			'''decode'''    ) else n for n in group.attrs['''%s%d''' % (name, chunk_id)]]    )
            chunk_id += 1
    return data





def 					__snake_case     (      _UpperCAmelCase    ):

    def _expand_single_ad_tensor(_UpperCAmelCase    ):
        if isinstance(_UpperCAmelCase       ,			tf.Tensor    ) and t.shape.rank == 1:
            return tf.expand_dims(_UpperCAmelCase       ,			axis=-1    )
        return t

    return tf.nest.map_structure(_expand_single_ad_tensor       ,			_UpperCAmelCase    )










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

__snake_case						:Dict						=					logging.get_logger(__name__)

@add_end_docstrings(__UpperCAmelCase   )
class    _A	(     __UpperCAmelCase   ):



       def __init__(		self							:					int					,		*__SCREAMING_SNAKE_CASE							:					Optional[int]					,		**__SCREAMING_SNAKE_CASE							:					str):


           '''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 		_lowerCamelCase      (		self							:					int					,		__SCREAMING_SNAKE_CASE							:					int=None					,		__SCREAMING_SNAKE_CASE							:					int=None					,		__SCREAMING_SNAKE_CASE							:					Tuple=None):


           '''simple docstring'''

           __a							=    {}
           __a							=    {}

           if prompt is not None:
               __a							=    prompt

           if generate_kwargs is not None:
               __a							=    generate_kwargs
           if max_new_tokens is not None:
               if "generate_kwargs" not in forward_kwargs:
                   __a							=    {}
               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''')
               __a							=    max_new_tokens
           return preprocess_params, forward_kwargs, {}



       def __call__(		self							:					Any					,		__SCREAMING_SNAKE_CASE							:					Union[str, List[str], "Image.Image", List["Image.Image"]]					,		**__SCREAMING_SNAKE_CASE							:					Any):


           '''simple docstring'''

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



       def 		_lowerCamelCase      (		self							:					Optional[int]					,		__SCREAMING_SNAKE_CASE							:					Dict					,		__SCREAMING_SNAKE_CASE							:					Optional[Any]=None):


           '''simple docstring'''

           __a							=    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.''')

               __a							=    self.model.config.model_type

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

               elif model_type == "pix2struct":
                   __a							=    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
                   __a							=    self.image_processor(images=__SCREAMING_SNAKE_CASE					,		return_tensors=self.framework)
                   __a							=    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:
               __a							=    self.image_processor(images=__SCREAMING_SNAKE_CASE					,		return_tensors=self.framework)

           if self.model.config.model_type == "git" and prompt is None:
               __a							=    None

           return model_inputs



       def 		_lowerCamelCase      (		self							:					List[Any]					,		__SCREAMING_SNAKE_CASE							:					str					,		__SCREAMING_SNAKE_CASE							:					Tuple=None):


           '''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'''])
           ):
               __a							=    None

           if generate_kwargs is None:
               __a							=    {}
           # 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.
           __a							=    model_inputs.pop(self.model.main_input_name)
           __a							=    self.model.generate(__SCREAMING_SNAKE_CASE					,		**__SCREAMING_SNAKE_CASE					,		**__SCREAMING_SNAKE_CASE)
           return model_outputs





       def 		_lowerCamelCase      (		self							:					str					,		__SCREAMING_SNAKE_CASE							:					Union[str, Any]):


           '''simple docstring'''

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





