




from typing import Dict

import numpy as np

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException


if is_tf_available():
							import tensorflow as tf

							from ..tf_utils import stable_softmax


if is_torch_available():
							import torch


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




@add_end_docstrings(
    UpperCamelCase__					,						r"""
        top_k (`int`, defaults to 5):
            The number of predictions to return.
        targets (`str` or `List[str]`, *optional*):
            When passed, the model will limit the scores to the passed targets instead of looking up in the whole
            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting
            token will be used (with a warning, and that might be slower).

    """					,						)
class 		__A      (			UpperCamelCase__			):

						def     A__						(		self   :Optional[int]    , __snake_case   :GenericTensor ):
										'''simple docstring'''

										if self.framework == "tf":
														__magic_name__	:	Dict								=tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()
										elif self.framework == "pt":
														__magic_name__	:	Tuple								=torch.nonzero(input_ids == self.tokenizer.mask_token_id    , as_tuple=__snake_case )
										else:
														raise ValueError("""Unsupported framework""" )
										return masked_index

						def     A__						(		self   :Any    , __snake_case   :GenericTensor ):
										'''simple docstring'''

										__magic_name__	:	Optional[int]								=self.get_masked_index(__snake_case )
										__magic_name__	:	Any								=np.prod(masked_index.shape )
										if numel < 1:
														raise PipelineException(
														    """fill-mask"""    , self.model.base_model_prefix    , f"No mask_token ({self.tokenizer.mask_token}) found on the input"    , )

						def     A__						(		self   :Optional[Any]    , __snake_case   :GenericTensor ):
										'''simple docstring'''

										if isinstance(__snake_case    , __snake_case ):
														for model_input in model_inputs:
																		self._ensure_exactly_one_mask_token(model_input["""input_ids"""][0] )
										else:
														for input_ids in model_inputs["input_ids"]:
																		self._ensure_exactly_one_mask_token(__snake_case )

						def     A__						(		self   :int    , __snake_case   :List[Any]    , __snake_case   :int=None    , **__snake_case   :Optional[Any] ):
										'''simple docstring'''

										if return_tensors is None:
														__magic_name__	:	int								=self.framework
										__magic_name__	:	List[str]								=self.tokenizer(__snake_case    , return_tensors=__snake_case )
										self.ensure_exactly_one_mask_token(__snake_case )
										return model_inputs

						def     A__						(		self   :Dict    , __snake_case   :List[str] ):
										'''simple docstring'''

										__magic_name__	:	Dict								=self.model(**__snake_case )
										__magic_name__	:	Union[str, Any]								=model_inputs["""input_ids"""]
										return model_outputs

						def     A__						(		self   :List[Any]    , __snake_case   :Dict    , __snake_case   :Dict=5    , __snake_case   :int=None ):
										'''simple docstring'''

										if target_ids is not None and target_ids.shape[0] < top_k:
														__magic_name__	:	int								=target_ids.shape[0]
										__magic_name__	:	Dict								=model_outputs["""input_ids"""][0]
										__magic_name__	:	str								=model_outputs["""logits"""]

										if self.framework == "tf":
														__magic_name__	:	str								=tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()[:, 0]

														__magic_name__	:	Any								=outputs.numpy()

														__magic_name__	:	Optional[Any]								=outputs[0, masked_index, :]
														__magic_name__	:	Any								=stable_softmax(__snake_case    , axis=-1 )
														if target_ids is not None:
																		__magic_name__	:	List[Any]								=tf.gather_nd(tf.squeeze(__snake_case    , 0 )    , target_ids.reshape(-1    , 1 ) )
																		__magic_name__	:	Any								=tf.expand_dims(__snake_case    , 0 )

														__magic_name__	:	str								=tf.math.top_k(__snake_case    , k=__snake_case )
														__magic_name__	:	Optional[Any]								=topk.values.numpy(), topk.indices.numpy()
										else:
														__magic_name__	:	List[Any]								=torch.nonzero(input_ids == self.tokenizer.mask_token_id    , as_tuple=__snake_case ).squeeze(-1 )
														# Fill mask pipeline supports only one ${mask_token} per sample

														__magic_name__	:	int								=outputs[0, masked_index, :]
														__magic_name__	:	Optional[int]								=logits.softmax(dim=-1 )
														if target_ids is not None:
																		__magic_name__	:	Any								=probs[..., target_ids]

														__magic_name__	:	Optional[int]								=probs.topk(__snake_case )

										__magic_name__	:	Tuple								=[]
										__magic_name__	:	str								=values.shape[0] == 1
										for i, (_values, _predictions) in enumerate(zip(values.tolist()    , predictions.tolist() ) ):
														__magic_name__	:	Any								=[]
														for v, p in zip(_values    , _predictions ):
																		# Copy is important since we're going to modify this array in place
																		__magic_name__	:	Optional[Any]								=input_ids.numpy().copy()
																		if target_ids is not None:
																						__magic_name__	:	Union[str, Any]								=target_ids[p].tolist()

																		__magic_name__	:	str								=p
																		# Filter padding out:
																		__magic_name__	:	str								=tokens[np.where(tokens != self.tokenizer.pad_token_id )]
																		# Originally we skip special tokens to give readable output.
																		# For multi masks though, the other [MASK] would be removed otherwise
																		# making the output look odd, so we add them back
																		__magic_name__	:	Tuple								=self.tokenizer.decode(__snake_case    , skip_special_tokens=__snake_case )
																		__magic_name__	:	Tuple								={"""score""": v, """token""": p, """token_str""": self.tokenizer.decode([p] ), """sequence""": sequence}
																		row.append(__snake_case )
														result.append(__snake_case )
										if single_mask:
														return result[0]
										return result

						def     A__						(		self   :Tuple    , __snake_case   :Any    , __snake_case   :str=None ):
										'''simple docstring'''

										if isinstance(__snake_case    , __snake_case ):
														__magic_name__	:	Optional[Any]								=[targets]
										try:
														__magic_name__	:	Union[str, Any]								=self.tokenizer.get_vocab()
										except Exception:
														__magic_name__	:	str								={}
										__magic_name__	:	Dict								=[]
										for target in targets:
														__magic_name__	:	Any								=vocab.get(__snake_case    , __snake_case )
														if id_ is None:
																		__magic_name__	:	Optional[Any]								=self.tokenizer(
																		    __snake_case    , add_special_tokens=__snake_case    , return_attention_mask=__snake_case    , return_token_type_ids=__snake_case    , max_length=1    , truncation=__snake_case    , )["""input_ids"""]
																		if len(__snake_case ) == 0:
																						logger.warning(
																						    f"The specified target token `{target}` does not exist in the model vocabulary. "
																						    """We cannot replace it with anything meaningful, ignoring it""" )
																						continue
																		__magic_name__	:	Union[str, Any]								=input_ids[0]
																		# XXX: If users encounter this pass
																		# it becomes pretty slow, so let's make sure
																		# The warning enables them to fix the input to
																		# get faster performance.
																		logger.warning(
																		    f"The specified target token `{target}` does not exist in the model vocabulary. "
																		    f"Replacing with `{self.tokenizer.convert_ids_to_tokens(id_ )}`." )
														target_ids.append(id_ )
										__magic_name__	:	Any								=list(set(__snake_case ) )
										if len(__snake_case ) == 0:
														raise ValueError("""At least one target must be provided when passed.""" )
										__magic_name__	:	Tuple								=np.array(__snake_case )
										return target_ids

						def     A__						(		self   :Optional[Any]    , __snake_case   :Optional[Any]=None    , __snake_case   :Dict=None ):
										'''simple docstring'''

										__magic_name__	:	Any								={}

										if targets is not None:
														__magic_name__	:	List[str]								=self.get_target_ids(__snake_case    , __snake_case )
														__magic_name__	:	Optional[int]								=target_ids

										if top_k is not None:
														__magic_name__	:	Union[str, Any]								=top_k

										if self.tokenizer.mask_token_id is None:
														raise PipelineException(
														    """fill-mask"""    , self.model.base_model_prefix    , """The tokenizer does not define a `mask_token`.""" )
										return {}, {}, postprocess_params


						def __call__(		self   :Union[str, Any]    , __snake_case   :Dict    , *__snake_case   :List[Any]    , **__snake_case   :Any ):
										'''simple docstring'''

										__magic_name__	:	List[str]								=super().__call__(__snake_case    , **__snake_case )
										if isinstance(__snake_case    , __snake_case ) and len(__snake_case ) == 1:
														return outputs[0]
										return outputs











import copy
import os
from typing import Union

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


UpperCAmelCase_		:				Union[str, Any]									=     logging.get_logger(__name__)

UpperCAmelCase_		:				Dict									=     {
    "google/pix2struct-textcaps-base": (
        "https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json"
    ),
}




class 		__A      (			UpperCamelCase__			):
						UpperCamelCase     						=					"""pix2struct_text_model"""
						UpperCamelCase     						=					["""past_key_values"""]
						UpperCamelCase     						=					{
						    """hidden_size""": """hidden_size""",
						    """num_attention_heads""": """num_heads""",
						    """num_hidden_layers""": """num_layers""",
						}

						def __init__(		self   :List[Any]    , __snake_case   :Dict=5_02_44    , __snake_case   :Dict=7_68    , __snake_case   :Union[str, Any]=64    , __snake_case   :Union[str, Any]=20_48    , __snake_case   :List[Any]=12    , __snake_case   :Any=12    , __snake_case   :str=32    , __snake_case   :Dict=1_28    , __snake_case   :Optional[int]=0.1    , __snake_case   :Any=1E-6    , __snake_case   :Optional[int]=1.0    , __snake_case   :List[Any]="gelu_new"    , __snake_case   :Any=0    , __snake_case   :Tuple=False    , __snake_case   :Any=0    , __snake_case   :int=1    , __snake_case   :Dict=False    , __snake_case   :Optional[Any]=True    , **__snake_case   :Dict    , ):
										'''simple docstring'''

										__magic_name__	:	List[str]								=vocab_size
										__magic_name__	:	List[str]								=hidden_size
										__magic_name__	:	Optional[int]								=d_kv
										__magic_name__	:	Dict								=d_ff
										__magic_name__	:	Tuple								=num_layers
										__magic_name__	:	str								=num_heads
										__magic_name__	:	Optional[Any]								=relative_attention_num_buckets
										__magic_name__	:	List[Any]								=relative_attention_max_distance
										__magic_name__	:	str								=dropout_rate
										__magic_name__	:	Optional[Any]								=layer_norm_epsilon
										__magic_name__	:	Union[str, Any]								=initializer_factor
										__magic_name__	:	Tuple								=use_cache

										__magic_name__	:	Any								=eos_token_id
										__magic_name__	:	int								=decoder_start_token_id

										# for backwards compatibility
										__magic_name__	:	Union[str, Any]								=dense_act_fn

										super().__init__(
										    pad_token_id=__snake_case    , eos_token_id=__snake_case    , decoder_start_token_id=__snake_case    , tie_word_embeddings=__snake_case    , is_decoder=__snake_case    , **__snake_case    , )


						@classmethod
						def     A__						(		cls   :Union[str, Any]    , __snake_case   :Union[str, os.PathLike]    , **__snake_case   :Any ):
										'''simple docstring'''

										cls._set_token_in_kwargs(__snake_case )

										__magic_name__				, __magic_name__	:	Optional[Any]								=cls.get_config_dict(__snake_case    , **__snake_case )

										# get the text config dict if we are loading from Pix2StructConfig
										if config_dict.get("""model_type""" ) == "pix2struct":
														__magic_name__	:	Tuple								=config_dict["""text_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(__snake_case    , **__snake_case )




class 		__A      (			UpperCamelCase__			):
						UpperCamelCase     						=					"""pix2struct_vision_model"""

						def __init__(		self   :Union[str, Any]    , __snake_case   :Tuple=7_68    , __snake_case   :Any=7_68    , __snake_case   :Tuple=20_48    , __snake_case   :Dict=64    , __snake_case   :List[str]=12    , __snake_case   :str=12    , __snake_case   :str="gelu_new"    , __snake_case   :Optional[int]=1E-6    , __snake_case   :Optional[int]=0.0    , __snake_case   :Any=0.0    , __snake_case   :Any=1E-10    , __snake_case   :List[str]=1.0    , __snake_case   :Tuple=40_96    , __snake_case   :Optional[int]=32    , __snake_case   :Union[str, Any]=1_28    , **__snake_case   :Optional[int]    , ):
										'''simple docstring'''

										super().__init__(**__snake_case )

										__magic_name__	:	Union[str, Any]								=hidden_size
										__magic_name__	:	Dict								=patch_embed_hidden_size
										__magic_name__	:	Tuple								=d_ff
										__magic_name__	:	str								=dropout_rate
										__magic_name__	:	str								=num_hidden_layers
										__magic_name__	:	Dict								=num_attention_heads
										__magic_name__	:	List[str]								=initializer_range
										__magic_name__	:	Optional[int]								=initializer_factor
										__magic_name__	:	str								=attention_dropout
										__magic_name__	:	Union[str, Any]								=layer_norm_eps
										__magic_name__	:	List[str]								=dense_act_fn
										__magic_name__	:	List[str]								=seq_len
										__magic_name__	:	str								=relative_attention_num_buckets
										__magic_name__	:	Optional[int]								=relative_attention_max_distance
										__magic_name__	:	List[str]								=d_kv


						@classmethod
						def     A__						(		cls   :Optional[Any]    , __snake_case   :Union[str, os.PathLike]    , **__snake_case   :Any ):
										'''simple docstring'''

										cls._set_token_in_kwargs(__snake_case )

										__magic_name__				, __magic_name__	:	Optional[int]								=cls.get_config_dict(__snake_case    , **__snake_case )

										# get the vision config dict if we are loading from Pix2StructConfig
										if config_dict.get("""model_type""" ) == "pix2struct":
														__magic_name__	:	int								=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(__snake_case    , **__snake_case )




class 		__A      (			UpperCamelCase__			):
						UpperCamelCase     						=					"""pix2struct"""
						UpperCamelCase     						=					True

						def __init__(		self   :Union[str, Any]    , __snake_case   :Optional[int]=None    , __snake_case   :List[Any]=None    , __snake_case   :Optional[Any]=1.0    , __snake_case   :Tuple=0.02    , __snake_case   :str=False    , __snake_case   :List[str]=False    , __snake_case   :str=True    , **__snake_case   :List[str]    , ):
										'''simple docstring'''

										super().__init__(tie_word_embeddings=__snake_case    , is_encoder_decoder=__snake_case    , **__snake_case )

										if text_config is None:
														__magic_name__	:	int								={}
														logger.info("""text_config is None. Initializing the Pix2StructTextConfig with default values.""" )

										if vision_config is None:
														__magic_name__	:	str								={}
														logger.info("""vision_config is None. Initializing the Pix2StructVisionConfig with default values.""" )

										__magic_name__	:	Union[str, Any]								=PixaStructTextConfig(**__snake_case )
										__magic_name__	:	str								=PixaStructVisionConfig(**__snake_case )

										__magic_name__	:	int								=self.text_config.decoder_start_token_id
										__magic_name__	:	Optional[Any]								=self.text_config.pad_token_id
										__magic_name__	:	str								=self.text_config.eos_token_id

										__magic_name__	:	int								=initializer_factor
										__magic_name__	:	List[Any]								=initializer_range

										__magic_name__	:	Dict								=self.initializer_range
										__magic_name__	:	Union[str, Any]								=self.initializer_range

										__magic_name__	:	Tuple								=is_vqa

						@classmethod
						def     A__						(		cls   :Optional[int]    , __snake_case   :PixaStructTextConfig    , __snake_case   :PixaStructVisionConfig    , **__snake_case   :List[str] ):
										'''simple docstring'''

										return cls(text_config=text_config.to_dict()    , vision_config=vision_config.to_dict()    , **__snake_case )


						def     A__						(		self   :Dict ):
										'''simple docstring'''

										__magic_name__	:	Union[str, Any]								=copy.deepcopy(self.__dict__ )
										__magic_name__	:	Any								=self.text_config.to_dict()
										__magic_name__	:	List[str]								=self.vision_config.to_dict()
										__magic_name__	:	Optional[int]								=self.__class__.model_type
										return output




