



# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer
from .base import PipelineTool


_lowerCamelCase         =	'''Here is a text containing a lot of information: \'\'\'{text}\'\'\'.

Can you answer this question about the text: \'{question}\''''

class    _SCREAMING_SNAKE_CASE						(_UpperCAmelCase			):
     lowerCAmelCase       =      "google/flan-t5-base"
     lowerCAmelCase       =      (
         "This is a tool that answers questions related to a text. It takes two arguments named `text`, which is the "
         "text where to find the answer, and `question`, which is the question, and returns the answer to the question."
     )
     lowerCAmelCase       =      "text_qa"
     lowerCAmelCase       =      AutoTokenizer
     lowerCAmelCase       =      AutoModelForSeqaSeqLM

     lowerCAmelCase       =      ["text", "text"]
     lowerCAmelCase       =      ["text"]





     def 						__snake_case     (							self			:				str  ,	UpperCamelCase			:				str  ,	UpperCamelCase			:				str					)->Optional[Any]:
      __SCREAMING_SNAKE_CASE							:     str							=						QA_PROMPT.format(text=_lowerCAmelCase  ,	question=_lowerCAmelCase					)
      return self.pre_processor(_lowerCAmelCase  ,	return_tensors="pt"					)





     def 						__snake_case     (							self			:				int  ,	UpperCamelCase			:				List[str]					)->int:
      __SCREAMING_SNAKE_CASE							:     Tuple							=						self.model.generate(**_lowerCAmelCase					)

      __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE							:     int							=						inputs["input_ids"].shape
      __SCREAMING_SNAKE_CASE							:     Dict							=						output_ids.shape[0]

      return output_ids.reshape(_lowerCAmelCase  ,	out_b // in_b  ,	*output_ids.shape[1:]					)[0][0]






     def 						__snake_case     (							self			:				List[Any]  ,	UpperCamelCase			:				str					)->Optional[Any]:
      return self.pre_processor.decode(_lowerCAmelCase  ,	skip_special_tokens=_lowerCAmelCase  ,	clean_up_tokenization_spaces=_lowerCAmelCase					)










from collections import OrderedDict
from dataclasses import fields
from typing import Any, Tuple

import numpy as np

from .import_utils import is_torch_available
def 				UpperCamelCase_	(					__snake_case      :    Dict  )->   str:




						'''simple docstring'''
						if is_torch_available():
												import torch

												if isinstance(__snake_case						,      torch.Tensor  ):
																		return True

						return isinstance(__snake_case						,      np.ndarray  )




class      __snake_case				(   _UpperCAmelCase):
					def 	a			(						self       :						Optional[Any]  )							->					Optional[Any]:



											'''simple docstring'''





											__magic_name__					=      fields(self  )

											# Safety and consistency checks
											if not len(_lowerCAmelCase  ):
																	raise ValueError(F'''{self.__class__.__name__} has no fields.'''  )

											__magic_name__					=      getattr(self	,      class_fields[0].name  )
											__magic_name__					=      all(getattr(self	,      field.name  ) is None for field in class_fields[1:]  )

											if other_fields_are_none and isinstance(_lowerCAmelCase	,      _lowerCAmelCase  ):
																	for key, value in first_field.items():
																							__magic_name__					=      value
											else:
																	for field in class_fields:
																							__magic_name__					=      getattr(self	,      field.name  )
																							if v is not None:
																													__magic_name__					=      v
					def __delitem__(						self       :						Dict	,      *_lowerCAmelCase       :						List[str]	,      **_lowerCAmelCase       :						List[str]  )							->					List[str]:



											'''simple docstring'''





											raise Exception(F'''You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.'''  )
					def 	a			(						self       :						Optional[int]	,      *_lowerCAmelCase       :						Optional[Any]	,      **_lowerCAmelCase       :						Optional[Any]  )							->					str:



											'''simple docstring'''





											raise Exception(F'''You cannot use ``setdefault`` on a {self.__class__.__name__} instance.'''  )
					def 	a			(						self       :						Union[str, Any]	,      *_lowerCAmelCase       :						List[str]	,      **_lowerCAmelCase       :						Any  )							->					str:



											'''simple docstring'''





											raise Exception(F'''You cannot use ``pop`` on a {self.__class__.__name__} instance.'''  )
					def 	a			(						self       :						Any	,      *_lowerCAmelCase       :						str	,      **_lowerCAmelCase       :						Optional[int]  )							->					List[Any]:



											'''simple docstring'''





											raise Exception(F'''You cannot use ``update`` on a {self.__class__.__name__} instance.'''  )
					def __getitem__(						self       :						Optional[Any]	,      _lowerCAmelCase       :						Any  )							->					Tuple:



											'''simple docstring'''





											if isinstance(_lowerCAmelCase	,      _lowerCAmelCase  ):
																	__magic_name__					=      dict(self.items()  )
																	return inner_dict[k]
											else:
																	return self.to_tuple()[k]
					def __setattr__(						self       :						str	,      _lowerCAmelCase       :						Optional[Any]	,      _lowerCAmelCase       :						Optional[int]  )							->					int:



											'''simple docstring'''





											if name in self.keys() and value is not None:
																	# Don't call self.__setitem__ to avoid recursion errors
																	super().__setitem__(_lowerCAmelCase	,      _lowerCAmelCase  )
											super().__setattr__(_lowerCAmelCase	,      _lowerCAmelCase  )
					def __setitem__(						self       :						Optional[Any]	,      _lowerCAmelCase       :						Optional[Any]	,      _lowerCAmelCase       :						List[str]  )							->					Optional[int]:



											'''simple docstring'''





											super().__setitem__(_lowerCAmelCase	,      _lowerCAmelCase  )
											# Don't call self.__setattr__ to avoid recursion errors
											super().__setattr__(_lowerCAmelCase	,      _lowerCAmelCase  )







					def 	a			(						self       :						str  )							->					Tuple[Any]:



											'''simple docstring'''





											return tuple(self[k] for k in self.keys()  )

