





"""simple docstring"""





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

_UpperCamelCase					      =   logging.get_logger(__name__)
@add_end_docstrings(UpperCAmelCase__ )
class 		SCREAMING_SNAKE_CASE_				(     UpperCAmelCase__ ):
				"""simple docstring"""




				def __init__(  self	:Tuple    ,     *__lowercase	:List[Any]    ,     **__lowercase	:List[Any]      ):
											super().__init__(*lowerCamelCase__    ,     **lowerCamelCase__      )
											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        __lowercase	(  self	:str    ,     __lowercase	:Any=None    ,     __lowercase	:List[Any]=None    ,     __lowercase	:str=None      ):
											__lowerCamelCase   :   Union[str, Any]       ={}
											__lowerCamelCase   :   Tuple       ={}

											if prompt is not None:
																		__lowerCamelCase   :   Optional[int]       =prompt

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




				def __call__(  self	:Union[str, Any]    ,     __lowercase	:Optional[int]    ,     **__lowercase	:Dict      ):
											return super().__call__(lowerCamelCase__    ,     **lowerCamelCase__      )




				def        __lowercase	(  self	:List[str]    ,     __lowercase	:int    ,     __lowercase	:List[Any]=None      ):
											__lowerCamelCase   :   Optional[int]       =load_image(lowerCamelCase__      )

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

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

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

																		elif model_type == "pix2struct":
																									__lowerCamelCase   :   Dict       =self.image_processor(images=lowerCamelCase__    ,     header_text=lowerCamelCase__    ,     return_tensors=self.framework      )

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

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

											else:
																		__lowerCamelCase   :   List[Any]       =self.image_processor(images=lowerCamelCase__    ,     return_tensors=self.framework      )

											if self.model.config.model_type == "git" and prompt is None:
																		__lowerCamelCase   :   Union[str, Any]       =None

											return model_inputs




				def        __lowercase	(  self	:List[Any]    ,     __lowercase	:int    ,     __lowercase	:Tuple=None      ):
											# Git model sets `model_inputs["input_ids"] = None` in `preprocess` (when `prompt=None`). In batch model, the
											# pipeline will group them into a list of `None`, which fail `_forward`. Avoid this by checking it first.
											if (
											    "input_ids" in model_inputs
											    and isinstance(model_inputs['''input_ids''']    ,     lowerCamelCase__      )
											    and all(x is None for x in model_inputs['''input_ids''']      )
											):
																		__lowerCamelCase   :   Union[str, Any]       =None

											if generate_kwargs is None:
																		__lowerCamelCase   :   Tuple       ={}
											# 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.
											__lowerCamelCase   :   Optional[Any]       =model_inputs.pop(self.model.main_input_name      )
											__lowerCamelCase   :   Optional[int]       =self.model.generate(lowerCamelCase__    ,     **lowerCamelCase__    ,     **lowerCamelCase__      )
											return model_outputs




				def        __lowercase	(  self	:Any    ,     __lowercase	:Union[str, Any]      ):
											__lowerCamelCase   :   Optional[Any]       =[]
											for output_ids in model_outputs:
																		__lowerCamelCase   :   Optional[Any]       ={
																		    "generated_text": self.tokenizer.decode(
																		        lowerCamelCase__    ,     skip_special_tokens=lowerCamelCase__    ,     )
																		}
																		records.append(lowerCamelCase__      )
											return records





from ...configuration_utils import PretrainedConfig
from ...utils import logging


a  :      List[Any]            =    logging.get_logger(__name__)

a  :      Union[str, Any]            =    {
    """bigcode/gpt_bigcode-santacoder""": """https://huggingface.co/bigcode/gpt_bigcode-santacoder/resolve/main/config.json""",
}

class 					_lowercase    (     UpperCAmelCase__			):






    '''simple docstring'''
    SCREAMING_SNAKE_CASE:				List[str]          =    'gpt_bigcode'
    SCREAMING_SNAKE_CASE:				Union[str, Any]          =    ['past_key_values']
    SCREAMING_SNAKE_CASE:				Tuple          =    {
        'hidden_size': 'n_embd',
        'max_position_embeddings': 'n_positions',
        'num_attention_heads': 'n_head',
        'num_hidden_layers': 'n_layer',
    }




    def __init__(    self       ,						lowerCamelCase__=50_257       ,						lowerCamelCase__=1_024       ,						lowerCamelCase__=768       ,						lowerCamelCase__=12       ,						lowerCamelCase__=12       ,						lowerCamelCase__=None       ,						lowerCamelCase__="gelu_pytorch_tanh"       ,						lowerCamelCase__=0.1       ,						lowerCamelCase__=0.1       ,						lowerCamelCase__=0.1       ,						lowerCamelCase__=1E-5       ,						lowerCamelCase__=0.0_2       ,						lowerCamelCase__=True       ,						lowerCamelCase__=True       ,						lowerCamelCase__=50_256       ,						lowerCamelCase__=50_256       ,						lowerCamelCase__=True       ,						lowerCamelCase__=True       ,						lowerCamelCase__=True       ,						**lowerCamelCase__       ,						):
       lowerCAmelCase_:							List[Any]       =	vocab_size
       lowerCAmelCase_:							List[str]       =	n_positions
       lowerCAmelCase_:							Union[str, Any]       =	n_embd
       lowerCAmelCase_:							Union[str, Any]       =	n_layer
       lowerCAmelCase_:							Union[str, Any]       =	n_head
       lowerCAmelCase_:							List[Any]       =	n_inner
       lowerCAmelCase_:							List[Any]       =	activation_function
       lowerCAmelCase_:							Optional[int]       =	resid_pdrop
       lowerCAmelCase_:							Union[str, Any]       =	embd_pdrop
       lowerCAmelCase_:							Any       =	attn_pdrop
       lowerCAmelCase_:							Union[str, Any]       =	layer_norm_epsilon
       lowerCAmelCase_:							Optional[Any]       =	initializer_range
       lowerCAmelCase_:							int       =	scale_attn_weights
       lowerCAmelCase_:							int       =	use_cache
       lowerCAmelCase_:							int       =	attention_softmax_in_fpaa
       lowerCAmelCase_:							int       =	scale_attention_softmax_in_fpaa
       lowerCAmelCase_:							Union[str, Any]       =	multi_query

       lowerCAmelCase_:							Union[str, Any]       =	bos_token_id
       lowerCAmelCase_:							List[str]       =	eos_token_id

       super().__init__(bos_token_id=lowerCamelCase__       ,						eos_token_id=lowerCamelCase__       ,						**lowerCamelCase__ )