
'''simple docstring'''






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

A			      =      logging.get_logger(__name__)




@add_end_docstrings(a__)
class     __snake_case		(   a__):
					def __init__(     self,    *A,    **A      ):

									"""simple docstring"""


									super().__init__(*A,    **A      )
									self.check_model_type(A      )
					def     UpperCAmelCase_							(     self,    A=None,    A=None,    A=None,    **A      ):

									"""simple docstring"""


									lowerCamelCase			, lowerCamelCase					:			int									= {}, {}
									if padding is not None:
													lowerCamelCase					:			Tuple									= padding
									if truncation is not None:
													lowerCamelCase					:			Optional[int]									= truncation
									if top_k is not None:
													lowerCamelCase					:			List[Any]									= top_k
									return preprocess_params, {}, postprocess_params
					def __call__(     self,    A,    A = None,    **A      ):

									"""simple docstring"""


									if isinstance(A,    (Image.Image, str)      ) and isinstance(A,    A      ):
													lowerCamelCase					:			str									= {'image': image, 'question': question}
									else:
													lowerCamelCase					:			Union[str, Any]									= image
									lowerCamelCase					:			List[Any]									= super().__call__(A,    **A      )
									return results
					def     UpperCAmelCase_							(     self,    A,    A=False,    A=False      ):

									"""simple docstring"""


									lowerCamelCase					:			Optional[int]									= load_image(inputs['image']      )
									lowerCamelCase					:			str									= self.tokenizer(
									    inputs['question'],    return_tensors=self.framework,    padding=A,    truncation=A      )
									lowerCamelCase					:			List[Any]									= self.image_processor(images=A,    return_tensors=self.framework      )
									model_inputs.update(A      )
									return model_inputs
					def     UpperCAmelCase_							(     self,    A      ):

									"""simple docstring"""


									lowerCamelCase					:			List[str]									= self.model(**A      )
									return model_outputs




					def     UpperCAmelCase_							(     self,    A,    A=5      ):

									"""simple docstring"""


									if top_k > self.model.config.num_labels:
													lowerCamelCase					:			Dict									= self.model.config.num_labels

									if self.framework == "pt":
													lowerCamelCase					:			Tuple									= model_outputs.logits.sigmoid()[0]
													lowerCamelCase			, lowerCamelCase					:			Dict									= probs.topk(A      )
									else:
													raise ValueError(F'''Unsupported framework: {self.framework}'''      )

									lowerCamelCase					:			str									= scores.tolist()
									lowerCamelCase					:			Optional[int]									= ids.tolist()
									return [{"score": score, "answer": self.model.config.idalabel[_id]} for score, _id in zip(A,    A      )]


'''simple docstring'''






import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


A			      =      logging.get_logger(__name__)


A			      =      '▁'

A			      =      {'vocab_file': 'spiece.model'}

A			      =      {
    'vocab_file': {
        'google/reformer-crime-and-punishment': (
            'https://huggingface.co/google/reformer-crime-and-punishment/resolve/main/spiece.model'
        )
    }
}

A			      =      {
    'google/reformer-crime-and-punishment': 52_4288,
}




class     __snake_case		(   a__):
					_lowerCAmelCase			     =	VOCAB_FILES_NAMES
					_lowerCAmelCase			     =	PRETRAINED_VOCAB_FILES_MAP
					_lowerCAmelCase			     =	PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
					_lowerCAmelCase			     =	['''input_ids''', '''attention_mask''']
					def __init__(     self,    A,    A="</s>",    A="<unk>",    A=[],    A = None,    **A,    ):

									"""simple docstring"""


									lowerCamelCase					:			str									= {} if sp_model_kwargs is None else sp_model_kwargs

									super().__init__(
									    eos_token=A,    unk_token=A,    additional_special_tokens=A,    sp_model_kwargs=self.sp_model_kwargs,    **A,    )

									lowerCamelCase					:			Any									= vocab_file
									lowerCamelCase					:			List[Any]									= spm.SentencePieceProcessor(**self.sp_model_kwargs      )
									self.sp_model.Load(A      )
					@property
					def     UpperCAmelCase_							(     self      ):

									"""simple docstring"""


									return self.sp_model.get_piece_size()
					def     UpperCAmelCase_							(     self      ):

									"""simple docstring"""


									lowerCamelCase					:			int									= {self.convert_ids_to_tokens(A      ): i for i in range(self.vocab_size      )}
									vocab.update(self.added_tokens_encoder      )
									return vocab
					def __getstate__(     self      ):

									"""simple docstring"""


									lowerCamelCase					:			Union[str, Any]									= self.__dict__.copy()
									lowerCamelCase					:			List[Any]									= None
									return state
					def __setstate__(     self,    A      ):

									"""simple docstring"""


									lowerCamelCase					:			int									= d

									# for backward compatibility
									if not hasattr(self,    'sp_model_kwargs'      ):
													lowerCamelCase					:			List[str]									= {}

									lowerCamelCase					:			Optional[int]									= spm.SentencePieceProcessor(**self.sp_model_kwargs      )
									self.sp_model.Load(self.vocab_file      )
					def     UpperCAmelCase_							(     self,    A      ):

									"""simple docstring"""


									return self.sp_model.encode(A,    out_type=A      )
					def     UpperCAmelCase_							(     self,    A      ):

									"""simple docstring"""


									return self.sp_model.piece_to_id(A      )
					def     UpperCAmelCase_							(     self,    A      ):

									"""simple docstring"""


									if index < self.sp_model.get_piece_size():
													lowerCamelCase					:			Union[str, Any]									= self.sp_model.IdToPiece(A      )
									return token
					def     UpperCAmelCase_							(     self,    A      ):

									"""simple docstring"""


									lowerCamelCase					:			Union[str, Any]									= []
									lowerCamelCase					:			Optional[int]									= ''
									for token in tokens:
													# make sure that special tokens are not decoded using sentencepiece model
													if token in self.all_special_tokens:
																	out_string += self.sp_model.decode(A      ) + token
																	lowerCamelCase					:			Any									= []
													else:
																	current_sub_tokens.append(A      )
									out_string += self.sp_model.decode(A      )
									return out_string.strip()




					def     UpperCAmelCase_							(     self,    A,    A = None      ):

									"""simple docstring"""


									if not os.path.isdir(A      ):
													logger.error(F'''Vocabulary path ({save_directory}) should be a directory'''      )
													return
									lowerCamelCase					:			str									= os.path.join(
									    A,    (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']      )

									if os.path.abspath(self.vocab_file      ) != os.path.abspath(A      ) and os.path.isfile(self.vocab_file      ):
													copyfile(self.vocab_file,    A      )
									elif not os.path.isfile(self.vocab_file      ):
													with open(A,    'wb'      ) as fi:
																	lowerCamelCase					:			Optional[Any]									= self.sp_model.serialized_model_proto()
																	fi.write(A      )

									return (out_vocab_file,)
