





from dataclasses import dataclass
from typing import Optional, Tuple

import torch
from torch import nn
from transformers import RobertaPreTrainedModel, XLMRobertaConfig, XLMRobertaModel
from transformers.utils import ModelOutput

@dataclass
class 		snake_case_   (							UpperCAmelCase_						):







	'''simple docstring'''
	__UpperCamelCase   =		None
	__UpperCamelCase   =		None
	__UpperCamelCase   =		None
	__UpperCamelCase   =		None





class 		snake_case_   (							UpperCAmelCase_						):







	'''simple docstring'''




	def __init__(						self							:     str					,      __lowerCamelCase							:     List[Any]=1					,      __lowerCamelCase							:     Any=0					,      __lowerCamelCase							:     List[Any]=2					,      __lowerCamelCase							:     Tuple=512					,      __lowerCamelCase							:     List[Any]="cls"					,      __lowerCamelCase							:     str=False					,      __lowerCamelCase							:     Optional[int]=True					,      **__lowerCamelCase							:     Dict					,      )       -> List[str]:

			'''simple docstring'''




			super().__init__(pad_token_id=__lowerCamelCase					,      bos_token_id=__lowerCamelCase					,      eos_token_id=__lowerCamelCase					,      **__lowerCamelCase   )
			__lowercase											=     project_dim
			__lowercase											=     pooler_fn
			__lowercase											=     learn_encoder
			__lowercase											=     use_attention_mask





class 		snake_case_   (							UpperCAmelCase_						):







	'''simple docstring'''
	__UpperCamelCase   =		[R'''pooler''', R'''logit_scale''']
	__UpperCamelCase   =		[R'''position_ids''', R'''predictions.decoder.bias''']
	__UpperCamelCase   =		'''roberta'''
	__UpperCamelCase   =		RobertaSeriesConfig




	def __init__(						self							:     Any					,      __lowerCamelCase							:     List[str]   )       -> Any:

			'''simple docstring'''




			super().__init__(__lowerCamelCase   )
			__lowercase											=     XLMRobertaModel(__lowerCamelCase   )
			__lowercase											=     nn.Linear(config.hidden_size					,      config.project_dim   )
			__lowercase											=     getattr(__lowerCamelCase					,      'has_pre_transformation'					,      __lowerCamelCase   )
			if self.has_pre_transformation:
					__lowercase											=     nn.Linear(config.hidden_size					,      config.project_dim   )
					__lowercase											=     nn.LayerNorm(config.hidden_size					,      eps=config.layer_norm_eps   )
			self.post_init()






	def    UpperCAmelCase			(						self							:     int					,      __lowerCamelCase							:     Optional[torch.Tensor] = None					,      __lowerCamelCase							:     Optional[torch.Tensor] = None					,      __lowerCamelCase							:     Optional[torch.Tensor] = None					,      __lowerCamelCase							:     Optional[torch.Tensor] = None					,      __lowerCamelCase							:     Optional[torch.Tensor] = None					,      __lowerCamelCase							:     Optional[torch.Tensor] = None					,      __lowerCamelCase							:     Optional[torch.Tensor] = None					,      __lowerCamelCase							:     Optional[torch.Tensor] = None					,      __lowerCamelCase							:     Optional[bool] = None					,      __lowerCamelCase							:     Optional[bool] = None					,      __lowerCamelCase							:     Optional[bool] = None					,      )       -> Union[str, Any]:

			'''simple docstring'''




			__lowercase											=     return_dict if return_dict is not None else self.config.use_return_dict

			__lowercase											=     self.base_model(
			    input_ids=__lowerCamelCase					,      attention_mask=__lowerCamelCase					,      token_type_ids=__lowerCamelCase					,      position_ids=__lowerCamelCase					,      head_mask=__lowerCamelCase					,      inputs_embeds=__lowerCamelCase					,      encoder_hidden_states=__lowerCamelCase					,      encoder_attention_mask=__lowerCamelCase					,      output_attentions=__lowerCamelCase					,      output_hidden_states=True if self.has_pre_transformation else output_hidden_states					,      return_dict=__lowerCamelCase					,      )

			if self.has_pre_transformation:
					__lowercase											=     outputs['hidden_states'][-2]
					__lowercase											=     self.pre_LN(__lowerCamelCase   )
					__lowercase											=     self.transformation_pre(__lowerCamelCase   )

					return TransformationModelOutput(
					    projection_state=__lowerCamelCase					,      last_hidden_state=outputs.last_hidden_state					,      hidden_states=outputs.hidden_states					,      attentions=outputs.attentions					,      )
			else:
					__lowercase											=     self.transformation(outputs.last_hidden_state   )
					return TransformationModelOutput(
					    projection_state=__lowerCamelCase					,      last_hidden_state=outputs.last_hidden_state					,      hidden_states=outputs.hidden_states					,      attentions=outputs.attentions					,      )











from typing import Union

from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
		from PIL import Image

		from ..image_utils import load_image

if is_torch_available():
		from ..models.auto.modeling_auto import MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING

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

@add_end_docstrings(UpperCAmelCase_						)
class 		snake_case_   (							UpperCAmelCase_						):







	'''simple docstring'''




	def __init__(						self							:     Optional[int]					,      *__lowerCamelCase							:     Optional[int]					,      **__lowerCamelCase							:     List[Any]   )       -> Optional[Any]:

			'''simple docstring'''




			super().__init__(*__lowerCamelCase					,      **__lowerCamelCase   )
			self.check_model_type(__lowerCamelCase   )




	def    UpperCAmelCase			(						self							:     Optional[int]					,      __lowerCamelCase							:     int=None					,      __lowerCamelCase							:     List[Any]=None					,      __lowerCamelCase							:     Any=None					,      **__lowerCamelCase							:     Optional[int]   )       -> Any:

			'''simple docstring'''




			__lowercase						,      __lowercase											=     {}, {}
			if padding is not None:
					__lowercase											=     padding
			if truncation is not None:
					__lowercase											=     truncation
			if top_k is not None:
					__lowercase											=     top_k
			return preprocess_params, {}, postprocess_params




	def __call__(						self							:     str					,      __lowerCamelCase							:     Union["Image.Image", str]					,      __lowerCamelCase							:     str = None					,      **__lowerCamelCase							:     Dict   )       -> Tuple:

			'''simple docstring'''




			if isinstance(__lowerCamelCase					,      (Image.Image, str)   ) and isinstance(__lowerCamelCase					,      __lowerCamelCase   ):
					__lowercase											=     {'image': image, 'question': question}
			else:
					__lowercase											=     image
			__lowercase											=     super().__call__(__lowerCamelCase					,      **__lowerCamelCase   )
			return results




	def    UpperCAmelCase			(						self							:     List[Any]					,      __lowerCamelCase							:     List[str]					,      __lowerCamelCase							:     Optional[Any]=False					,      __lowerCamelCase							:     Optional[Any]=False   )       -> Optional[int]:

			'''simple docstring'''




			__lowercase											=     load_image(inputs['image']   )
			__lowercase											=     self.tokenizer(
			    inputs['question']					,      return_tensors=self.framework					,      padding=__lowerCamelCase					,      truncation=__lowerCamelCase   )
			__lowercase											=     self.image_processor(images=__lowerCamelCase					,      return_tensors=self.framework   )
			model_inputs.update(__lowerCamelCase   )
			return model_inputs




	def    UpperCAmelCase			(						self							:     str					,      __lowerCamelCase							:     Tuple   )       -> Any:

			'''simple docstring'''




			__lowercase											=     self.model(**__lowerCamelCase   )
			return model_outputs






	def    UpperCAmelCase			(						self							:     int					,      __lowerCamelCase							:     Any					,      __lowerCamelCase							:     int=5   )       -> Tuple:

			'''simple docstring'''




			if top_k > self.model.config.num_labels:
					__lowercase											=     self.model.config.num_labels

			if self.framework == "pt":
					__lowercase											=     model_outputs.logits.sigmoid()[0]
					__lowercase						,      __lowercase											=     probs.topk(__lowerCamelCase   )
			else:
					raise ValueError(F"Unsupported framework: {self.framework}"   )

			__lowercase											=     scores.tolist()
			__lowercase											=     ids.tolist()
			return [{"score": score, "answer": self.model.config.idalabel[_id]} for score, _id in zip(__lowerCamelCase					,      __lowerCamelCase   )]




