




# 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


SCREAMING_SNAKE_CASE_						:					int			   =       '''Here is a text containing a lot of information: \'\'\'{text}\'\'\'.\n\nCan you answer this question about the text: \'{question}\''''







class 		__UpperCAmelCase(		__UpperCAmelCase ):





     """simple docstring"""



     __UpperCAmelCase	: int						=    """google/flan-t5-base"""
     __UpperCAmelCase	: Any						=    (
         """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	: str						=    """text_qa"""
     __UpperCAmelCase	: List[str]						=    AutoTokenizer
     __UpperCAmelCase	: Any						=    AutoModelForSeqaSeqLM

     __UpperCAmelCase	: int						=    ["""text""", """text"""]
     __UpperCAmelCase	: int						=    ["""text"""]

     def 				__SCREAMING_SNAKE_CASE		(      self :       List[str]						,				A :       Tuple						,				A :       Tuple    )			->			Tuple:






         """simple docstring"""
         a__      =       QA_PROMPT.format(text=lowercase_						,				question=lowercase_    )
         return self.pre_processor(lowercase_						,				return_tensors="""pt"""    )

     def 				__SCREAMING_SNAKE_CASE		(      self :       List[Any]						,				A :       Tuple    )			->			Optional[int]:






         """simple docstring"""
         a__      =       self.model.generate(**lowercase_    )

         a__      =       inputs['''input_ids'''].shape
         a__      =       output_ids.shape[0]

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






     def 				__SCREAMING_SNAKE_CASE		(      self :       Optional[Any]						,				A :       List[str]    )			->			Any:






         """simple docstring"""
         return self.pre_processor.decode(lowercase_						,				skip_special_tokens=lowercase_						,				clean_up_tokenization_spaces=lowercase_    )












import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
 import torch

if is_vision_available():
 from PIL import Image

 from transformers import SwinaSRImageProcessor
 from transformers.image_transforms import get_image_size







class 		__UpperCAmelCase(		unittest.TestCase ):





     """simple docstring"""



     def __init__(      self :       Optional[int]						,				A :       Dict						,				A :       Union[str, Any]=7						,				A :       List[str]=3						,				A :       Optional[int]=18						,				A :       Optional[int]=30						,				A :       Optional[Any]=4_00						,				A :       Optional[Any]=True						,				A :       Tuple=1 / 2_55						,				A :       Tuple=True						,				A :       Optional[int]=8						,				)			->			Any:






         """simple docstring"""
         a__      =       parent
         a__      =       batch_size
         a__      =       num_channels
         a__      =       image_size
         a__      =       min_resolution
         a__      =       max_resolution
         a__      =       do_rescale
         a__      =       rescale_factor
         a__      =       do_pad
         a__      =       pad_size

     def 				__SCREAMING_SNAKE_CASE		(      self :       List[Any]    )			->			Union[str, Any]:






         """simple docstring"""
         return {
             "do_rescale": self.do_rescale,
             "rescale_factor": self.rescale_factor,
             "do_pad": self.do_pad,
             "pad_size": self.pad_size,
         }






     def 				__SCREAMING_SNAKE_CASE		(      self :       int						,				A :       int=False						,				A :       Any=False						,				A :       List[Any]=False    )			->			Optional[Any]:






         """simple docstring"""
         assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

         if equal_resolution:
             a__      =       []
             for i in range(self.batch_size    ):
                 image_inputs.append(
                     np.random.randint(
                         2_55						,				size=(self.num_channels, self.max_resolution, self.max_resolution)						,				dtype=np.uinta    )    )
         else:
             a__      =       []
             for i in range(self.batch_size    ):
                 a__ ,		a__      =       np.random.choice(np.arange(self.min_resolution						,				self.max_resolution    )						,				2    )
                 image_inputs.append(np.random.randint(2_55						,				size=(self.num_channels, width, height)						,				dtype=np.uinta    )    )

         if not numpify and not torchify:
             # PIL expects the channel dimension as last dimension
             a__      =       [Image.fromarray(np.moveaxis(A						,				0						,				-1    )    ) for x in image_inputs]

         if torchify:
             a__      =       [torch.from_numpy(A    ) for x in image_inputs]

         return image_inputs







@require_torch
@require_vision
class 		__UpperCAmelCase(		lowercase__       ,	unittest.TestCase ):





     """simple docstring"""



     __UpperCAmelCase	: Dict						=    SwinaSRImageProcessor if is_vision_available() else None

     def 				__SCREAMING_SNAKE_CASE		(      self :       int    )			->			Dict:






         """simple docstring"""
         a__      =       SwinaSRImageProcessingTester(self    )

     @property
     def 				__SCREAMING_SNAKE_CASE		(      self :       List[Any]    )			->			List[Any]:






         """simple docstring"""
         return self.image_processor_tester.prepare_image_processor_dict()

     def 				__SCREAMING_SNAKE_CASE		(      self :       Tuple    )			->			int:






         """simple docstring"""
         a__      =       self.image_processing_class(**self.image_processor_dict    )
         self.assertTrue(hasattr(A						,				"""do_rescale"""    )    )
         self.assertTrue(hasattr(A						,				"""rescale_factor"""    )    )
         self.assertTrue(hasattr(A						,				"""do_pad"""    )    )
         self.assertTrue(hasattr(A						,				"""pad_size"""    )    )

     def 				__SCREAMING_SNAKE_CASE		(      self :       Dict    )			->			List[Any]:






         """simple docstring"""
         pass

     def 				__SCREAMING_SNAKE_CASE		(      self :       int						,				A :       Optional[Any]    )			->			List[str]:






         """simple docstring"""
         a__ ,		a__      =       get_image_size(A    )
         a__      =       self.image_processor_tester.pad_size

         a__      =       (old_height // size + 1) * size - old_height
         a__      =       (old_width // size + 1) * size - old_width
         return old_height + pad_height, old_width + pad_width

     def 				__SCREAMING_SNAKE_CASE		(      self :       Any    )			->			Union[str, Any]:






         """simple docstring"""
         # Initialize image_processor
         a__      =       self.image_processing_class(**self.image_processor_dict    )
         # create random PIL images
         a__      =       self.image_processor_tester.prepare_inputs(equal_resolution=A    )
         for image in image_inputs:
             self.assertIsInstance(A						,				Image.Image    )

         # Test not batched input
         a__      =       image_processor(image_inputs[0]						,				return_tensors="""pt"""    ).pixel_values
         a__ ,		a__      =       self.calculate_expected_size(np.array(image_inputs[0]    )    )
         self.assertEqual(
             encoded_images.shape						,				(
                 1,
                 self.image_processor_tester.num_channels,
                 expected_height,
                 expected_width,
             )						,				)

     def 				__SCREAMING_SNAKE_CASE		(      self :       Union[str, Any]    )			->			Optional[Any]:






         """simple docstring"""
         # Initialize image_processor
         a__      =       self.image_processing_class(**self.image_processor_dict    )
         # create random numpy tensors
         a__      =       self.image_processor_tester.prepare_inputs(equal_resolution=A						,				numpify=A    )
         for image in image_inputs:
             self.assertIsInstance(A						,				np.ndarray    )

         # Test not batched input
         a__      =       image_processor(image_inputs[0]						,				return_tensors="""pt"""    ).pixel_values
         a__ ,		a__      =       self.calculate_expected_size(image_inputs[0]    )
         self.assertEqual(
             encoded_images.shape						,				(
                 1,
                 self.image_processor_tester.num_channels,
                 expected_height,
                 expected_width,
             )						,				)






     def 				__SCREAMING_SNAKE_CASE		(      self :       Union[str, Any]    )			->			Tuple:






         """simple docstring"""
         # Initialize image_processor
         a__      =       self.image_processing_class(**self.image_processor_dict    )
         # create random PyTorch tensors
         a__      =       self.image_processor_tester.prepare_inputs(equal_resolution=A						,				torchify=A    )
         for image in image_inputs:
             self.assertIsInstance(A						,				torch.Tensor    )

         # Test not batched input
         a__      =       image_processor(image_inputs[0]						,				return_tensors="""pt"""    ).pixel_values
         a__ ,		a__      =       self.calculate_expected_size(image_inputs[0]    )
         self.assertEqual(
             encoded_images.shape						,				(
                 1,
                 self.image_processor_tester.num_channels,
                 expected_height,
                 expected_width,
             )						,				)






