

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, prepare_image_inputs


if is_torch_available():
       import torch

if is_vision_available():
       from PIL import Image

       from transformers import ConvNextImageProcessor
class     SCREAMING_SNAKE_CASE__     (						unittest.TestCase		):





       '''simple docstring'''




       def __init__(						self       :						str    ,		lowerCAmelCase__       :						List[str]    ,		lowerCAmelCase__       :						Optional[int]=7    ,		lowerCAmelCase__       :						Dict=3    ,		lowerCAmelCase__       :						Tuple=18    ,		lowerCAmelCase__       :						Optional[Any]=30    ,		lowerCAmelCase__       :						Any=400    ,		lowerCAmelCase__       :						str=True    ,		lowerCAmelCase__       :						int=None    ,		lowerCAmelCase__       :						List[str]=0.875    ,		lowerCAmelCase__       :						Union[str, Any]=True    ,		lowerCAmelCase__       :						str=[0.5, 0.5, 0.5]    ,		lowerCAmelCase__       :						List[str]=[0.5, 0.5, 0.5]    ,		)			->    Any:
             snake_case__					=   size if size is not None else {"""shortest_edge""": 20}
             snake_case__					=   parent
             snake_case__					=   batch_size
             snake_case__					=   num_channels
             snake_case__					=   image_size
             snake_case__					=   min_resolution
             snake_case__					=   max_resolution
             snake_case__					=   do_resize
             snake_case__					=   size
             snake_case__					=   crop_pct
             snake_case__					=   do_normalize
             snake_case__					=   image_mean
             snake_case__					=   image_std

       def UpperCAmelCase_						(						self       :						int							)			->    str:
             return {
                 "image_mean": self.image_mean,
                 "image_std": self.image_std,
                 "do_normalize": self.do_normalize,
                 "do_resize": self.do_resize,
                 "size": self.size,
                 "crop_pct": self.crop_pct,
             }



@require_torch
@require_vision
class     SCREAMING_SNAKE_CASE__     (						__a ,	unittest.TestCase		):





       '''simple docstring'''




       UpperCamelCase__ :     List[Any]				    =       ConvNextImageProcessor if is_vision_available() else None

       def UpperCAmelCase_						(						self       :						int							)			->    Optional[Any]:
             snake_case__					=   ConvNextImageProcessingTester(self							)

       @property
       def UpperCAmelCase_						(						self       :						Any							)			->    Union[str, Any]:
             return self.image_processor_tester.prepare_image_processor_dict()

       def UpperCAmelCase_						(						self       :						Dict							)			->    Any:
             snake_case__					=   self.image_processing_class(**self.image_processor_dict							)
             self.assertTrue(hasattr(lowerCAmelCase__    ,		"""do_resize"""							)							)
             self.assertTrue(hasattr(lowerCAmelCase__    ,		"""size"""							)							)
             self.assertTrue(hasattr(lowerCAmelCase__    ,		"""crop_pct"""							)							)
             self.assertTrue(hasattr(lowerCAmelCase__    ,		"""do_normalize"""							)							)
             self.assertTrue(hasattr(lowerCAmelCase__    ,		"""image_mean"""							)							)
             self.assertTrue(hasattr(lowerCAmelCase__    ,		"""image_std"""							)							)

       def UpperCAmelCase_						(						self       :						str							)			->    Dict:
             snake_case__					=   self.image_processing_class.from_dict(self.image_processor_dict							)
             self.assertEqual(image_processor.size    ,		{"""shortest_edge""": 20}							)

             snake_case__					=   self.image_processing_class.from_dict(self.image_processor_dict    ,		size=42							)
             self.assertEqual(image_processor.size    ,		{"""shortest_edge""": 42}							)

       def UpperCAmelCase_						(						self       :						str							)			->    Optional[Any]:
             pass

       def UpperCAmelCase_						(						self       :						Optional[Any]							)			->    Any:
             # Initialize image_processing
             snake_case__					=   self.image_processing_class(**self.image_processor_dict							)
             # create random PIL images
             snake_case__					=   prepare_image_inputs(self.image_processor_tester    ,		equal_resolution=lowerCAmelCase__							)
             for image in image_inputs:
                   self.assertIsInstance(lowerCAmelCase__    ,		Image.Image							)

             # Test not batched input
             snake_case__					=   image_processing(image_inputs[0]    ,		return_tensors="""pt"""							).pixel_values
             self.assertEqual(
                 encoded_images.shape    ,		(
                     1,
                     self.image_processor_tester.num_channels,
                     self.image_processor_tester.size["""shortest_edge"""],
                     self.image_processor_tester.size["""shortest_edge"""],
                 )    ,		)

             # Test batched
             snake_case__					=   image_processing(lowerCAmelCase__    ,		return_tensors="""pt"""							).pixel_values
             self.assertEqual(
                 encoded_images.shape    ,		(
                     self.image_processor_tester.batch_size,
                     self.image_processor_tester.num_channels,
                     self.image_processor_tester.size["""shortest_edge"""],
                     self.image_processor_tester.size["""shortest_edge"""],
                 )    ,		)

       def UpperCAmelCase_						(						self       :						int							)			->    Any:
             # Initialize image_processing
             snake_case__					=   self.image_processing_class(**self.image_processor_dict							)
             # create random numpy tensors
             snake_case__					=   prepare_image_inputs(self.image_processor_tester    ,		equal_resolution=lowerCAmelCase__    ,		numpify=lowerCAmelCase__							)
             for image in image_inputs:
                   self.assertIsInstance(lowerCAmelCase__    ,		np.ndarray							)

             # Test not batched input
             snake_case__					=   image_processing(image_inputs[0]    ,		return_tensors="""pt"""							).pixel_values
             self.assertEqual(
                 encoded_images.shape    ,		(
                     1,
                     self.image_processor_tester.num_channels,
                     self.image_processor_tester.size["""shortest_edge"""],
                     self.image_processor_tester.size["""shortest_edge"""],
                 )    ,		)

             # Test batched
             snake_case__					=   image_processing(lowerCAmelCase__    ,		return_tensors="""pt"""							).pixel_values
             self.assertEqual(
                 encoded_images.shape    ,		(
                     self.image_processor_tester.batch_size,
                     self.image_processor_tester.num_channels,
                     self.image_processor_tester.size["""shortest_edge"""],
                     self.image_processor_tester.size["""shortest_edge"""],
                 )    ,		)

       def UpperCAmelCase_						(						self       :						str							)			->    List[str]:
             # Initialize image_processing
             snake_case__					=   self.image_processing_class(**self.image_processor_dict							)
             # create random PyTorch tensors
             snake_case__					=   prepare_image_inputs(self.image_processor_tester    ,		equal_resolution=lowerCAmelCase__    ,		torchify=lowerCAmelCase__							)
             for image in image_inputs:
                   self.assertIsInstance(lowerCAmelCase__    ,		torch.Tensor							)

             # Test not batched input
             snake_case__					=   image_processing(image_inputs[0]    ,		return_tensors="""pt"""							).pixel_values
             self.assertEqual(
                 encoded_images.shape    ,		(
                     1,
                     self.image_processor_tester.num_channels,
                     self.image_processor_tester.size["""shortest_edge"""],
                     self.image_processor_tester.size["""shortest_edge"""],
                 )    ,		)

             # Test batched
             snake_case__					=   image_processing(lowerCAmelCase__    ,		return_tensors="""pt"""							).pixel_values
             self.assertEqual(
                 encoded_images.shape    ,		(
                     self.image_processor_tester.batch_size,
                     self.image_processor_tester.num_channels,
                     self.image_processor_tester.size["""shortest_edge"""],
                     self.image_processor_tester.size["""shortest_edge"""],
                 )    ,		)









# 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[Any]										=    '''Here is a text containing a lot of information: \'\'\'{text}\'\'\'.

Can you answer this question about the text: \'{question}\''''
class     SCREAMING_SNAKE_CASE__     (						__a		):





       '''simple docstring'''




       UpperCamelCase__ :     int				    =       '''google/flan-t5-base'''
       UpperCamelCase__ :     int				    =       (
           '''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__ :     Tuple				    =       '''text_qa'''
       UpperCamelCase__ :     Tuple				    =       AutoTokenizer
       UpperCamelCase__ :     List[Any]				    =       AutoModelForSeqaSeqLM

       UpperCamelCase__ :     Optional[Any]				    =       ['''text''', '''text''']
       UpperCamelCase__ :     Any				    =       ['''text''']

       def UpperCAmelCase_						(						self       :						Tuple    ,		lowerCAmelCase__       :						str    ,		lowerCAmelCase__       :						str							)			->    List[Any]:
             snake_case__					=   QA_PROMPT.format(text=lowerCAmelCase__    ,		question=lowerCAmelCase__							)
             return self.pre_processor(lowerCAmelCase__    ,		return_tensors="""pt"""							)

       def UpperCAmelCase_						(						self       :						Optional[Any]    ,		lowerCAmelCase__       :						Dict							)			->    List[Any]:
             snake_case__					=   self.model.generate(**lowerCAmelCase__							)

             snake_case__	,			snake_case__					=   inputs["""input_ids"""].shape
             snake_case__					=   output_ids.shape[0]

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

       def UpperCAmelCase_						(						self       :						Union[str, Any]    ,		lowerCAmelCase__       :						Dict							)			->    List[Any]:
             return self.pre_processor.decode(lowerCAmelCase__    ,		skip_special_tokens=lowerCAmelCase__    ,		clean_up_tokenization_spaces=lowerCAmelCase__							)






