


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


lowerCAmelCase           =		logging.get_logger(__name__)

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





class       A    (   A_ ):
							UpperCamelCase_   :							Tuple       ='''instructblip_vision_model'''


							def __init__(self      ,				lowerCAmelCase=1_4_0_8      ,				lowerCAmelCase=6_1_4_4      ,				lowerCAmelCase=3_9      ,				lowerCAmelCase=1_6      ,				lowerCAmelCase=2_2_4      ,				lowerCAmelCase=1_4      ,				lowerCAmelCase="gelu"      ,				lowerCAmelCase=1E-6      ,				lowerCAmelCase=0.0      ,				lowerCAmelCase=1E-10      ,				lowerCAmelCase=True      ,				**lowerCAmelCase      ,				):
									super().__init__(**lowerCAmelCase					)

									__lowercase=			hidden_size
									__lowercase=			intermediate_size
									__lowercase=			num_hidden_layers
									__lowercase=			num_attention_heads
									__lowercase=			patch_size
									__lowercase=			image_size
									__lowercase=			initializer_range
									__lowercase=			attention_dropout
									__lowercase=			layer_norm_eps
									__lowercase=			hidden_act
									__lowercase=			qkv_bias







							@classmethod
							def 			_A       (cls      ,				lowerCAmelCase      ,				**lowerCAmelCase					):
									cls._set_token_in_kwargs(lowerCAmelCase					)

									__lowercase,							__lowercase=			cls.get_config_dict(lowerCAmelCase      ,				**lowerCAmelCase					)

									# get the vision config dict if we are loading from InstructBlipConfig
									if config_dict.get('model_type'					) == "instructblip":
											__lowercase=			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    (   A_ ):
							UpperCamelCase_   :							Union[str, Any]       ='''instructblip_qformer'''


							def __init__(self      ,				lowerCAmelCase=3_0_5_2_2      ,				lowerCAmelCase=7_6_8      ,				lowerCAmelCase=1_2      ,				lowerCAmelCase=1_2      ,				lowerCAmelCase=3_0_7_2      ,				lowerCAmelCase="gelu"      ,				lowerCAmelCase=0.1      ,				lowerCAmelCase=0.1      ,				lowerCAmelCase=5_1_2      ,				lowerCAmelCase=0.02      ,				lowerCAmelCase=1E-12      ,				lowerCAmelCase=0      ,				lowerCAmelCase="absolute"      ,				lowerCAmelCase=2      ,				lowerCAmelCase=1_4_0_8      ,				**lowerCAmelCase      ,				):
									super().__init__(pad_token_id=lowerCAmelCase      ,				**lowerCAmelCase					)

									__lowercase=			vocab_size
									__lowercase=			hidden_size
									__lowercase=			num_hidden_layers
									__lowercase=			num_attention_heads
									__lowercase=			hidden_act
									__lowercase=			intermediate_size
									__lowercase=			hidden_dropout_prob
									__lowercase=			attention_probs_dropout_prob
									__lowercase=			max_position_embeddings
									__lowercase=			initializer_range
									__lowercase=			layer_norm_eps
									__lowercase=			position_embedding_type
									__lowercase=			cross_attention_frequency
									__lowercase=			encoder_hidden_size







							@classmethod
							def 			_A       (cls      ,				lowerCAmelCase      ,				**lowerCAmelCase					):
									cls._set_token_in_kwargs(lowerCAmelCase					)

									__lowercase,							__lowercase=			cls.get_config_dict(lowerCAmelCase      ,				**lowerCAmelCase					)

									# get the qformer config dict if we are loading from InstructBlipConfig
									if config_dict.get('model_type'					) == "instructblip":
											__lowercase=			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    (   A_ ):
							UpperCamelCase_   :							str       ='''instructblip'''
							UpperCamelCase_   :							Optional[int]       =True


							def __init__(self      ,				lowerCAmelCase=None      ,				lowerCAmelCase=None      ,				lowerCAmelCase=None      ,				lowerCAmelCase=3_2      ,				**lowerCAmelCase					):
									super().__init__(**lowerCAmelCase					)

									if vision_config is None:
											__lowercase=			{}
											logger.info('vision_config is None. initializing the InstructBlipVisionConfig with default values.'					)

									if qformer_config is None:
											__lowercase=			{}
											logger.info('qformer_config is None. Initializing the InstructBlipQFormerConfig with default values.'					)

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

									__lowercase=			InstructBlipVisionConfig(**lowerCAmelCase					)
									__lowercase=			InstructBlipQFormerConfig(**lowerCAmelCase					)
									__lowercase=			text_config['model_type'] if 'model_type' in text_config else 'opt'
									__lowercase=			CONFIG_MAPPING[text_model_type](**lowerCAmelCase					)

									__lowercase=			self.text_config.tie_word_embeddings
									__lowercase=			self.text_config.is_encoder_decoder

									__lowercase=			num_query_tokens
									__lowercase=			self.vision_config.hidden_size
									__lowercase=			self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
									__lowercase=			1.0
									__lowercase=			0.02


							@classmethod
							def 			_A       (cls      ,				lowerCAmelCase      ,				lowerCAmelCase      ,				lowerCAmelCase      ,				**lowerCAmelCase      ,				):
									return cls(
									    vision_config=vision_config.to_dict()      ,				qformer_config=qformer_config.to_dict()      ,				text_config=text_config.to_dict()      ,				**lowerCAmelCase      ,				)







							def 			_A       (self					):
									__lowercase=			copy.deepcopy(self.__dict__					)
									__lowercase=			self.vision_config.to_dict()
									__lowercase=			self.qformer_config.to_dict()
									__lowercase=			self.text_config.to_dict()
									__lowercase=			self.__class__.model_type
									return output










import enum
import warnings

from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING
from ..utils import add_end_docstrings, is_tf_available
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
	import tensorflow as tf





class       A    (   enum.Enum ):
							UpperCamelCase_   :							Optional[int]       =0
							UpperCamelCase_   :							Tuple       =1
							UpperCamelCase_   :							Optional[int]       =2





@add_end_docstrings(A_ )
class       A    (   A_ ):
							UpperCamelCase_   :							Union[str, Any]       ='''
    In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The
    voice of Nicholas\'s young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western
    Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision
    and denounces one of the men as a horse thief. Although his father initially slaps him for making such an
    accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of
    the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,
    begging for his blessing. <eod> </s> <eos>
    '''


							def __init__(self      ,				*lowerCAmelCase      ,				**lowerCAmelCase					):
									super().__init__(*lowerCAmelCase      ,				**lowerCAmelCase					)
									self.check_model_type(
									    TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == 'tf' else MODEL_FOR_CAUSAL_LM_MAPPING					)
									if "prefix" not in self._preprocess_params:
											# This is very specific. The logic is quite complex and needs to be done
											# as a "default".
											# It also defines both some preprocess_kwargs and generate_kwargs
											# which is why we cannot put them in their respective methods.
											__lowercase=			None
											if self.model.config.prefix is not None:
													__lowercase=			self.model.config.prefix
											if prefix is None and self.model.__class__.__name__ in [
											    "XLNetLMHeadModel",
											    "TransfoXLLMHeadModel",
											    "TFXLNetLMHeadModel",
											    "TFTransfoXLLMHeadModel",
											]:
													# For XLNet and TransformerXL we add an article to the prompt to give more state to the model.
													__lowercase=			self.XL_PREFIX
											if prefix is not None:
													# Recalculate some generate_kwargs linked to prefix.
													__lowercase,							__lowercase,							__lowercase=			self._sanitize_parameters(prefix=lowerCAmelCase      ,				**self._forward_params					)
													__lowercase=			{**self._preprocess_params, **preprocess_params}
													__lowercase=			{**self._forward_params, **forward_params}


							def 			_A       (self      ,				lowerCAmelCase=None      ,				lowerCAmelCase=None      ,				lowerCAmelCase=None      ,				lowerCAmelCase=None      ,				lowerCAmelCase=None      ,				lowerCAmelCase=None      ,				lowerCAmelCase=None      ,				lowerCAmelCase=None      ,				**lowerCAmelCase      ,				):
									__lowercase=			{}
									if prefix is not None:
											__lowercase=			prefix
									if prefix:
											__lowercase=			self.tokenizer(
											    lowerCAmelCase      ,				padding=lowerCAmelCase      ,				add_special_tokens=lowerCAmelCase      ,				return_tensors=self.framework					)
											__lowercase=			prefix_inputs['input_ids'].shape[-1]

									if handle_long_generation is not None:
											if handle_long_generation not in {"hole"}:
													raise ValueError(
													    f'{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected'
													    ' [None, \'hole\']'					)
											__lowercase=			handle_long_generation

									preprocess_params.update(lowerCAmelCase					)
									__lowercase=			generate_kwargs

									__lowercase=			{}
									if return_full_text is not None and return_type is None:
											if return_text is not None:
													raise ValueError('`return_text` is mutually exclusive with `return_full_text`'					)
											if return_tensors is not None:
													raise ValueError('`return_full_text` is mutually exclusive with `return_tensors`'					)
											__lowercase=			ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT
									if return_tensors is not None and return_type is None:
											if return_text is not None:
													raise ValueError('`return_text` is mutually exclusive with `return_tensors`'					)
											__lowercase=			ReturnType.TENSORS
									if return_type is not None:
											__lowercase=			return_type
									if clean_up_tokenization_spaces is not None:
											__lowercase=			clean_up_tokenization_spaces

									if stop_sequence is not None:
											__lowercase=			self.tokenizer.encode(lowerCAmelCase      ,				add_special_tokens=lowerCAmelCase					)
											if len(lowerCAmelCase					) > 1:
													warnings.warn(
													    'Stopping on a multiple token sequence is not yet supported on transformers. The first token of'
													    ' the stop sequence will be used as the stop sequence string in the interim.'					)
											__lowercase=			stop_sequence_ids[0]

									return preprocess_params, forward_params, postprocess_params


							def 			_A       (self      ,				*lowerCAmelCase      ,				**lowerCAmelCase					):
									# Parse arguments
									if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
											kwargs.update({'add_space_before_punct_symbol': True}					)

									return super()._parse_and_tokenize(*lowerCAmelCase      ,				**lowerCAmelCase					)


							def __call__(self      ,				lowerCAmelCase      ,				**lowerCAmelCase					):
									return super().__call__(lowerCAmelCase      ,				**lowerCAmelCase					)


							def 			_A       (self      ,				lowerCAmelCase      ,				lowerCAmelCase=""      ,				lowerCAmelCase=None      ,				**lowerCAmelCase					):
									__lowercase=			self.tokenizer(
									    prefix + prompt_text      ,				padding=lowerCAmelCase      ,				add_special_tokens=lowerCAmelCase      ,				return_tensors=self.framework					)
									__lowercase=			prompt_text

									if handle_long_generation == "hole":
											__lowercase=			inputs['input_ids'].shape[-1]
											if "max_new_tokens" in generate_kwargs:
													__lowercase=			generate_kwargs['max_new_tokens']
											else:
													__lowercase=			generate_kwargs.get('max_length'      ,				self.model.config.max_length					) - cur_len
													if new_tokens < 0:
															raise ValueError('We cannot infer how many new tokens are expected'					)
											if cur_len + new_tokens > self.tokenizer.model_max_length:
													__lowercase=			self.tokenizer.model_max_length - new_tokens
													if keep_length <= 0:
															raise ValueError(
															    'We cannot use `hole` to handle this generation the number of desired tokens exceeds the'
															    ' models max length'					)

													__lowercase=			inputs['input_ids'][:, -keep_length:]
													if "attention_mask" in inputs:
															__lowercase=			inputs['attention_mask'][:, -keep_length:]

									return inputs


							def 			_A       (self      ,				lowerCAmelCase      ,				**lowerCAmelCase					):
									__lowercase=			model_inputs['input_ids']
									__lowercase=			model_inputs.get('attention_mask'      ,				lowerCAmelCase					)
									# Allow empty prompts
									if input_ids.shape[1] == 0:
											__lowercase=			None
											__lowercase=			None
											__lowercase=			1
									else:
											__lowercase=			input_ids.shape[0]
									__lowercase=			model_inputs.pop('prompt_text'					)

									# If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying
									# generate_kwargs, as some of the parameterization may come from the initialization of the pipeline.
									__lowercase=			generate_kwargs.pop('prefix_length'      ,				0					)
									if prefix_length > 0:
											__lowercase=			'max_new_tokens' in generate_kwargs or (
											    'generation_config' in generate_kwargs
											    and generate_kwargs['generation_config'].max_new_tokens is not None
											)
											if not has_max_new_tokens:
													__lowercase=			generate_kwargs.get('max_length'					) or self.model.config.max_length
													generate_kwargs["max_length"] += prefix_length
											__lowercase=			'min_new_tokens' in generate_kwargs or (
											    'generation_config' in generate_kwargs
											    and generate_kwargs['generation_config'].min_new_tokens is not None
											)
											if not has_min_new_tokens and "min_length" in generate_kwargs:
													generate_kwargs["min_length"] += prefix_length

        # BS x SL
									__lowercase=			self.model.generate(input_ids=lowerCAmelCase      ,				attention_mask=lowerCAmelCase      ,				**lowerCAmelCase					)
									__lowercase=			generated_sequence.shape[0]
									if self.framework == "pt":
											__lowercase=			generated_sequence.reshape(lowerCAmelCase      ,				out_b // in_b      ,				*generated_sequence.shape[1:]					)
									elif self.framework == "tf":
											__lowercase=			tf.reshape(lowerCAmelCase      ,				(in_b, out_b // in_b, *generated_sequence.shape[1:])					)
									return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text}







							def 			_A       (self      ,				lowerCAmelCase      ,				lowerCAmelCase=ReturnType.FULL_TEXT      ,				lowerCAmelCase=True					):
									__lowercase=			model_outputs['generated_sequence'][0]
									__lowercase=			model_outputs['input_ids']
									__lowercase=			model_outputs['prompt_text']
									__lowercase=			generated_sequence.numpy().tolist()
									__lowercase=			[]
									for sequence in generated_sequence:
											if return_type == ReturnType.TENSORS:
													__lowercase=			{'generated_token_ids': sequence}
											elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}:
													# Decode text
													__lowercase=			self.tokenizer.decode(
													    lowerCAmelCase      ,				skip_special_tokens=lowerCAmelCase      ,				clean_up_tokenization_spaces=lowerCAmelCase      ,				)

													# Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used
													if input_ids is None:
															__lowercase=			0
													else:
															__lowercase=			len(
															    self.tokenizer.decode(
															        input_ids[0]      ,				skip_special_tokens=lowerCAmelCase      ,				clean_up_tokenization_spaces=lowerCAmelCase      ,				)					)

													if return_type == ReturnType.FULL_TEXT:
															__lowercase=			prompt_text + text[prompt_length:]
													else:
															__lowercase=			text[prompt_length:]

													__lowercase=			{'generated_text': all_text}
											records.append(lowerCAmelCase					)

									return records






