




# 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 :    List[str]      						=      "Here is a text containing a lot of information: '''{text}'''.\n\nCan you answer this question about the text: '{question}'"


class  lowerCamelCase     (		lowercase__    ):






			'''simple docstring'''





			UpperCamelCase__										='''google/flan-t5-base'''
			UpperCamelCase__										=(
			    '''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.'''
			)
			UpperCamelCase__										='''text_qa'''
			UpperCamelCase__										=AutoTokenizer
			UpperCamelCase__										=AutoModelForSeqaSeqLM

			UpperCamelCase__										=['''text''', '''text''']
			UpperCamelCase__										=['''text''']

			def 				UpperCAmelCase__							(			self      : List[Any]							,    lowerCamelCase_      : str							,    lowerCamelCase_      : str	)    -> Union[str, Any]:
								__magic_name__				:						int     				=				QA_PROMPT.format(text=__lowerCamelCase							,    question=__lowerCamelCase	)
								return self.pre_processor(__lowerCamelCase							,    return_tensors='''pt'''	)

			def 				UpperCAmelCase__							(			self      : Any							,    lowerCamelCase_      : Optional[Any]	)    -> Union[str, Any]:
								__magic_name__				:						Tuple     				=				self.model.generate(**__lowerCamelCase	)

								__magic_name__				:						str     				=				inputs["input_ids"].shape
								__magic_name__				:						int     				=				output_ids.shape[0]

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


			def 				UpperCAmelCase__							(			self      : Optional[int]							,    lowerCamelCase_      : List[str]	)    -> List[str]:
								return self.pre_processor.decode(__lowerCamelCase							,    skip_special_tokens=__lowerCamelCase							,    clean_up_tokenization_spaces=__lowerCamelCase	)







import torch

from transformers import AutoTokenizer







class      _lowercase					(				lowercase__):


       """simple docstring"""




       def __init__(  self				:     Optional[Any]   , __lowerCamelCase				:     Dict			):


             '''simple docstring'''



             lowerCamelCase__						:							int       =    AutoTokenizer.from_pretrained(__lowerCamelCase			)





       def 		lowerCAmelCase	(  self				:     Union[str, Any]   , __lowerCamelCase				:     str			):


             '''simple docstring'''



             if isinstance(__lowerCamelCase   , __lowerCamelCase			) and all(isinstance(_x   , __lowerCamelCase			) for _x in x			):
                   lowerCamelCase__						:							List[Any]       =    None
                   for l in x:
                         lowerCamelCase__						:							str       =    self.tokenizer(
                             __lowerCamelCase   , padding="max_length"   , max_length=384   , truncation=__lowerCamelCase   , return_tensors="pt"   , )
                         lowerCamelCase__						:							Dict       =    torch.tensor([len(__lowerCamelCase			)]			)
                         if d is not None:
                               for k in d.keys():
                                     lowerCamelCase__						:							Tuple       =    torch.cat((d[k], t[k])   , 0			)
                         else:
                               lowerCamelCase__						:							Union[str, Any]       =    t

                   lowerCamelCase__						:							List[Any]       =    torch.tensor(self.tokenizer.convert_tokens_to_ids("[E]"			)			)
                   lowerCamelCase__						:							Dict       =    torch.tensor(self.tokenizer.convert_tokens_to_ids("[/E]"			)			)

             elif isinstance(__lowerCamelCase   , __lowerCamelCase			) and all(isinstance(_x   , __lowerCamelCase			) for _x in x			):
                   lowerCamelCase__						:							Tuple       =    self.tokenizer(
                       __lowerCamelCase   , padding="max_length"   , max_length=384   , truncation=__lowerCamelCase   , return_tensors="pt"   , )

             else:
                   raise Exception(
                       "Type of parameter x was not recognized! Only `list of strings` for query or `list of lists of"
                       " strings` for supports are supported."			)

             return d





       def 		lowerCAmelCase	(  self				:     List[Any]   , __lowerCamelCase				:     List[str]   , __lowerCamelCase				:     List[str]   , __lowerCamelCase				:     Dict   , __lowerCamelCase				:     Any   , __lowerCamelCase				:     Optional[Any]=0.7_0			):


             '''simple docstring'''



             lowerCamelCase__						:							Union[str, Any]       =    []
             for idx in range(len(W_query["input_ids"]			)			):
                   lowerCamelCase__						:							str       =    range(p_start.shape[1]			)

                   lowerCamelCase__						:							int       =    []
                   for start_id in start_indexes:
                         for end_id in end_indexes:
                               if start_id < end_id:
                                     output.append(
                                         (
                                             start_id,
                                             end_id,
                                             p_start[idx][start_id].item(),
                                             p_end[idx][end_id].item(),
                                         )			)

                   output.sort(key=lambda __lowerCamelCase			: (tup[2] * tup[3])   , reverse=__lowerCamelCase			)
                   lowerCamelCase__						:							str       =    []
                   for k in range(len(__lowerCamelCase			)			):
                         if output[k][2] * output[k][3] >= thresh:
                               lowerCamelCase__       ,  lowerCamelCase__						:							Optional[int]       =    output[k][0], output[k][1]
                               lowerCamelCase__						:							Tuple       =    self.tokenizer.decode(W_query["input_ids"][idx][c_start_pos:c_end_pos]			)
                               temp.append((decoded, output[k][2] * output[k][3])			)

                   final_outputs.append(__lowerCamelCase			)

             return final_outputs


