




"""simple docstring"""







import enum
import warnings

from ..tokenization_utils import TruncationStrategy
from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
						import tensorflow as tf

						from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING

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

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




class    lowerCAmelCase__							(      enum.Enum     ):


				"""simple docstring"""





				__UpperCAmelCase			:  int			   =   0
				__UpperCAmelCase			:  Tuple			   =   1





@add_end_docstrings(UpperCAmelCase_     )
class    lowerCAmelCase__							(      UpperCAmelCase_     ):


				"""simple docstring"""





				__UpperCAmelCase			:  Any			   =   "generated"



				def __init__(  self       :						List[Any]     , *lowercase__       :						List[Any]     , **lowercase__       :						int    ):
						super().__init__(*__lowerCamelCase     , **__lowerCamelCase    )

						self.check_model_type(
						    TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
						    if self.framework == "tf"
						    else MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING    )



				def    snake_case     (  self       :						Dict     , lowercase__       :						int=None     , lowercase__       :						Optional[Any]=None     , lowercase__       :						Union[str, Any]=None     , lowercase__       :						Optional[int]=None     , lowercase__       :						int=None     , lowercase__       :						int=None     , **lowercase__       :						int     , ):
						__lowercase					:		Optional[Any]        =					{}
						if truncation is not None:
								__lowercase					:		Union[str, Any]        =					truncation

						__lowercase					:		List[Any]        =					generate_kwargs

						__lowercase					:		Optional[int]        =					{}
						if return_tensors is not None and return_type is None:
								__lowercase					:		Optional[Any]        =					ReturnType.TENSORS if return_tensors else ReturnType.TEXT
						if return_type is not None:
								__lowercase					:		Optional[int]        =					return_type

						if clean_up_tokenization_spaces is not None:
								__lowercase					:		List[Any]        =					clean_up_tokenization_spaces

						if stop_sequence is not None:
								__lowercase					:		Optional[int]        =					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					:		Union[str, Any]        =					stop_sequence_ids[0]

						return preprocess_params, forward_params, postprocess_params



				def    snake_case     (  self       :						Dict     , lowercase__       :						int     , lowercase__       :						int     , lowercase__       :						int    ):
						return True



				def    snake_case     (  self       :						Dict     , *lowercase__       :						List[str]     , lowercase__       :						List[Any]    ):
						__lowercase					:		List[Any]        =					self.model.config.prefix if self.model.config.prefix is not None else ""
						if isinstance(args[0]     , __lowerCamelCase    ):
								if self.tokenizer.pad_token_id is None:
										raise ValueError("Please make sure that the tokenizer has a pad_token_id when using a batch input"    )
								__lowercase					:		Union[str, Any]        =					([prefix + arg for arg in args[0]],)
								__lowercase					:		Any        =					True

						elif isinstance(args[0]     , __lowerCamelCase    ):
								__lowercase					:		Optional[int]        =					(prefix + args[0],)
								__lowercase					:		List[str]        =					False
						else:
								raise ValueError(
								    f' `args[0]`: {args[0]} have the wrong format. The should be either of type `str` or type `list`'    )
						__lowercase					:		Optional[int]        =					self.tokenizer(*__lowerCamelCase     , padding=__lowerCamelCase     , truncation=__lowerCamelCase     , return_tensors=self.framework    )
						# This is produced by tokenizers but is an invalid generate kwargs
						if "token_type_ids" in inputs:
								del inputs["token_type_ids"]
						return inputs



				def __call__(  self       :						str     , *lowercase__       :						Optional[int]     , **lowercase__       :						int    ):
						__lowercase					:		List[str]        =					super().__call__(*__lowerCamelCase     , **__lowerCamelCase    )
						if (
						    isinstance(args[0]     , __lowerCamelCase    )
						    and all(isinstance(__lowerCamelCase     , __lowerCamelCase    ) for el in args[0]    )
						    and all(len(__lowerCamelCase    ) == 1 for res in result    )
						):
								return [res[0] for res in result]
						return result



				def    snake_case     (  self       :						Optional[int]     , lowercase__       :						List[str]     , lowercase__       :						Any=TruncationStrategy.DO_NOT_TRUNCATE     , **lowercase__       :						Optional[int]    ):
						__lowercase					:		List[Any]        =					self._parse_and_tokenize(__lowerCamelCase     , truncation=__lowerCamelCase     , **__lowerCamelCase    )
						return inputs



				def    snake_case     (  self       :						Optional[Any]     , lowercase__       :						List[Any]     , **lowercase__       :						Tuple    ):




						if self.framework == "pt":
								__lowercase    ,__lowercase					:		List[str]        =					model_inputs["input_ids"].shape
						elif self.framework == "tf":
								__lowercase    ,__lowercase					:		int        =					tf.shape(model_inputs["input_ids"]    ).numpy()

						__lowercase					:		int        =					generate_kwargs.get("min_length"     , self.model.config.min_length    )
						__lowercase					:		Any        =					generate_kwargs.get("max_length"     , self.model.config.max_length    )
						self.check_inputs(__lowerCamelCase     , generate_kwargs["min_length"]     , generate_kwargs["max_length"]    )
						__lowercase					:		List[str]        =					self.model.generate(**__lowerCamelCase     , **__lowerCamelCase    )
						__lowercase					:		str        =					output_ids.shape[0]
						if self.framework == "pt":
								__lowercase					:		Optional[int]        =					output_ids.reshape(__lowerCamelCase     , out_b // in_b     , *output_ids.shape[1:]    )
						elif self.framework == "tf":
								__lowercase					:		Optional[int]        =					tf.reshape(__lowerCamelCase     , (in_b, out_b // in_b, *output_ids.shape[1:])    )
						return {"output_ids": output_ids}



				def    snake_case     (  self       :						str     , lowercase__       :						Union[str, Any]     , lowercase__       :						List[Any]=ReturnType.TEXT     , lowercase__       :						Optional[int]=False    ):
						__lowercase					:		Optional[int]        =					[]
						for output_ids in model_outputs["output_ids"][0]:
								if return_type == ReturnType.TENSORS:
										__lowercase					:		Union[str, Any]        =					{f'{self.return_name}_token_ids': output_ids}
								elif return_type == ReturnType.TEXT:
										__lowercase					:		List[str]        =					{
										    f'{self.return_name}_text': self.tokenizer.decode(
										        __lowerCamelCase     , skip_special_tokens=__lowerCamelCase     , clean_up_tokenization_spaces=__lowerCamelCase     , )
										}
								records.append(__lowerCamelCase    )
						return records





@add_end_docstrings(UpperCAmelCase_     )
class    lowerCAmelCase__							(      UpperCAmelCase_     ):


				"""simple docstring"""





				__UpperCAmelCase			:  Optional[int]			   =   "summary"



				def __call__(  self       :						Dict     , *lowercase__       :						Optional[int]     , **lowercase__       :						List[Any]    ):
						return super().__call__(*__lowerCamelCase     , **__lowerCamelCase    )



				def    snake_case     (  self       :						Optional[int]     , lowercase__       :						int     , lowercase__       :						int     , lowercase__       :						int    ):




						if max_length < min_length:
								logger.warning(f'Your min_length={min_length} must be inferior than your max_length={max_length}.'    )

						if input_length < max_length:
								logger.warning(
								    f'Your max_length is set to {max_length}, but your input_length is only {input_length}. Since this is '
								    "a summarization task, where outputs shorter than the input are typically wanted, you might "
								    f'consider decreasing max_length manually, e.g. summarizer(\'...\', max_length={input_length//2})'    )





@add_end_docstrings(UpperCAmelCase_     )
class    lowerCAmelCase__							(      UpperCAmelCase_     ):


				"""simple docstring"""





				__UpperCAmelCase			:  Optional[int]			   =   "translation"



				def    snake_case     (  self       :						List[str]     , lowercase__       :						int     , lowercase__       :						int     , lowercase__       :						int    ):




						if input_length > 0.9 * max_length:
								logger.warning(
								    f'Your input_length: {input_length} is bigger than 0.9 * max_length: {max_length}. You might consider '
								    "increasing your max_length manually, e.g. translator(\'...\', max_length=400)"    )
						return True



				def    snake_case     (  self       :						Dict     , *lowercase__       :						Dict     , lowercase__       :						Optional[Any]=TruncationStrategy.DO_NOT_TRUNCATE     , lowercase__       :						str=None     , lowercase__       :						Tuple=None    ):




						if getattr(self.tokenizer     , "_build_translation_inputs"     , __lowerCamelCase    ):
								return self.tokenizer._build_translation_inputs(
								    *__lowerCamelCase     , return_tensors=self.framework     , truncation=__lowerCamelCase     , src_lang=__lowerCamelCase     , tgt_lang=__lowerCamelCase    )
						else:
								return super()._parse_and_tokenize(*__lowerCamelCase     , truncation=__lowerCamelCase    )



				def    snake_case     (  self       :						Tuple     , lowercase__       :						Dict=None     , lowercase__       :						List[Any]=None     , **lowercase__       :						Optional[int]    ):
						__lowercase    ,__lowercase    ,__lowercase					:		List[str]        =					super()._sanitize_parameters(**__lowerCamelCase    )
						if src_lang is not None:
								__lowercase					:		int        =					src_lang
						if tgt_lang is not None:
								__lowercase					:		List[Any]        =					tgt_lang
						if src_lang is None and tgt_lang is None:
								# Backward compatibility, direct arguments use is preferred.
								__lowercase					:		Dict        =					kwargs.get("task"     , self.task    )
								__lowercase					:		List[Any]        =					task.split("_"    )
								if task and len(__lowerCamelCase    ) == 4:
										# translation, XX, to YY
										__lowercase					:		List[str]        =					items[1]
										__lowercase					:		str        =					items[3]
						return preprocess_params, forward_params, postprocess_params



				def __call__(  self       :						str     , *lowercase__       :						Union[str, Any]     , **lowercase__       :						Union[str, Any]    ):
						return super().__call__(*__lowerCamelCase     , **__lowerCamelCase    )







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   )]




