


'''simple docstring'''

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   __lowerCAmelCase						(unittest.TestCase					):





      '''simple docstring'''






      def __init__(self   :   List[Any]       ,						UpperCamelCase   :   Optional[Any]       ,						UpperCamelCase   :   Any=7       ,						UpperCamelCase   :   Union[str, Any]=3       ,						UpperCamelCase   :   Dict=18       ,						UpperCamelCase   :   Any=30       ,						UpperCamelCase   :   Any=400       ,						UpperCamelCase   :   Optional[Any]=True       ,						UpperCamelCase   :   List[str]=1 / 255       ,						UpperCamelCase   :   Any=True       ,						UpperCamelCase   :   Tuple=8       ,						):

             '''simple docstring'''







             lowercase__				      =			parent
             lowercase__				      =			batch_size
             lowercase__				      =			num_channels
             lowercase__				      =			image_size
             lowercase__				      =			min_resolution
             lowercase__				      =			max_resolution
             lowercase__				      =			do_rescale
             lowercase__				      =			rescale_factor
             lowercase__				      =			do_pad
             lowercase__				      =			pad_size



      def 				UpperCamelCase__		(self   :   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 				UpperCamelCase__		(self   :   Optional[int]       ,						UpperCamelCase   :   int=False       ,						UpperCamelCase   :   Optional[int]=False       ,						UpperCamelCase   :   Union[str, Any]=False			):

             '''simple docstring'''







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

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

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

             if torchify:
                    lowercase__				      =			[torch.from_numpy(UpperCamelCase			) for x in image_inputs]

             return image_inputs






@require_torch
@require_vision
class   __lowerCAmelCase						(lowercase_  ,					unittest.TestCase					):





      '''simple docstring'''






      lowerCAmelCase__ :					Tuple   =							SwinaSRImageProcessor if is_vision_available() else None



      def 				UpperCamelCase__		(self   :   Dict			):

             '''simple docstring'''







             lowercase__				      =			SwinaSRImageProcessingTester(self			)



      @property
      def 				UpperCamelCase__		(self   :   Dict			):

             '''simple docstring'''







             return self.image_processor_tester.prepare_image_processor_dict()



      def 				UpperCamelCase__		(self   :   Any			):

             '''simple docstring'''







             lowercase__				      =			self.image_processing_class(**self.image_processor_dict			)
             self.assertTrue(hasattr(UpperCamelCase       ,						'''do_rescale'''			)			)
             self.assertTrue(hasattr(UpperCamelCase       ,						'''rescale_factor'''			)			)
             self.assertTrue(hasattr(UpperCamelCase       ,						'''do_pad'''			)			)
             self.assertTrue(hasattr(UpperCamelCase       ,						'''pad_size'''			)			)



      def 				UpperCamelCase__		(self   :   Optional[int]			):

             '''simple docstring'''







             pass



      def 				UpperCamelCase__		(self   :   List[Any]       ,						UpperCamelCase   :   str			):

             '''simple docstring'''







             lowercase__      ,lowercase__				      =			get_image_size(UpperCamelCase			)
             lowercase__				      =			self.image_processor_tester.pad_size

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



      def 				UpperCamelCase__		(self   :   Optional[Any]			):

             '''simple docstring'''







             lowercase__				      =			self.image_processing_class(**self.image_processor_dict			)
             # create random PIL images
             lowercase__				      =			self.image_processor_tester.prepare_inputs(equal_resolution=UpperCamelCase			)
             for image in image_inputs:
                    self.assertIsInstance(UpperCamelCase       ,						Image.Image			)

             # Test not batched input
             lowercase__				      =			image_processor(image_inputs[0]       ,						return_tensors='''pt'''			).pixel_values
             lowercase__      ,lowercase__				      =			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 				UpperCamelCase__		(self   :   str			):

             '''simple docstring'''







             lowercase__				      =			self.image_processing_class(**self.image_processor_dict			)
             # create random numpy tensors
             lowercase__				      =			self.image_processor_tester.prepare_inputs(equal_resolution=UpperCamelCase       ,						numpify=UpperCamelCase			)
             for image in image_inputs:
                    self.assertIsInstance(UpperCamelCase       ,						np.ndarray			)

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






      def 				UpperCamelCase__		(self   :   Optional[Any]			):

             '''simple docstring'''







             lowercase__				      =			self.image_processing_class(**self.image_processor_dict			)
             # create random PyTorch tensors
             lowercase__				      =			self.image_processor_tester.prepare_inputs(equal_resolution=UpperCamelCase       ,						torchify=UpperCamelCase			)
             for image in image_inputs:
                    self.assertIsInstance(UpperCamelCase       ,						torch.Tensor			)

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








'''simple docstring'''

# 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							:       Any  						=     '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'''






      lowerCAmelCase__ :					Dict   =							"""google/flan-t5-base"""
      lowerCAmelCase__ :					List[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."""
      )
      lowerCAmelCase__ :					Any   =							"""text_qa"""
      lowerCAmelCase__ :					Union[str, Any]   =							AutoTokenizer
      lowerCAmelCase__ :					Any   =							AutoModelForSeqaSeqLM

      lowerCAmelCase__ :					Any   =							["""text""", """text"""]
      lowerCAmelCase__ :					Optional[int]   =							["""text"""]



      def 				UpperCamelCase__		(self   :   Union[str, Any]       ,						UpperCamelCase   :   str       ,						UpperCamelCase   :   str			):

             '''simple docstring'''







             lowercase__				      =			QA_PROMPT.format(text=UpperCamelCase       ,						question=UpperCamelCase			)
             return self.pre_processor(UpperCamelCase       ,						return_tensors='''pt'''			)



      def 				UpperCamelCase__		(self   :   Dict       ,						UpperCamelCase   :   List[Any]			):

             '''simple docstring'''







             lowercase__				      =			self.model.generate(**UpperCamelCase			)

             lowercase__      ,lowercase__				      =			inputs['''input_ids'''].shape
             lowercase__				      =			output_ids.shape[0]

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






      def 				UpperCamelCase__		(self   :   Tuple       ,						UpperCamelCase   :   Optional[Any]			):

             '''simple docstring'''







             return self.pre_processor.decode(UpperCamelCase       ,						skip_special_tokens=UpperCamelCase       ,						clean_up_tokenization_spaces=UpperCamelCase			)




