




'''simple docstring'''
import json
import os
import tempfile

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


if is_torch_available():
  import numpy as np
  import torch

if is_vision_available():
  from PIL import Image
def     snake_case_  (       a__		:     List[Any]   ,a__		:     Union[str, Any]=False   ,a__		:     Tuple=False   ,a__		:     Union[str, Any]=False      ):



    """simple docstring"""




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

    __lowercase          =						[]
    for i in range(image_processor_tester.batch_size      ):
        if equal_resolution:
            __lowercase          =						__lowercase          =						image_processor_tester.max_resolution
        else:
            # To avoid getting image width/height 0
            __lowercase          =						image_processor_tester.min_resolution
            if getattr(a__   ,"""size_divisor"""   ,a__      ):
                # If `size_divisor` is defined, the image needs to have width/size >= `size_divisor`
                __lowercase          =						max(image_processor_tester.size_divisor   ,a__      )
            __lowercase    ,__lowercase          =						np.random.choice(np.arange(a__   ,image_processor_tester.max_resolution      )   ,2      )
        image_inputs.append(
            np.random.randint(2_55   ,size=(image_processor_tester.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(a__   ,0   ,-1      )      ) for image in image_inputs]

    if torchify:
        __lowercase          =						[torch.from_numpy(a__      ) for image in image_inputs]

    return image_inputs
def     snake_case_  (       a__		:     Tuple   ,a__		:     List[str]=10   ,a__		:     Optional[Any]=10   ,a__		:     Dict=False   ,a__		:     Dict=False      ):



    """simple docstring"""




    __lowercase          =						[]
    for i in range(image_processor_tester.num_frames      ):
        video.append(np.random.randint(2_55   ,size=(image_processor_tester.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(a__   ,0   ,-1      )      ) for frame in video]

    if torchify:
        __lowercase          =						[torch.from_numpy(a__      ) for frame in video]

    return video
def     snake_case_  (       a__		:     Dict   ,a__		:     Optional[Any]=False   ,a__		:     Union[str, Any]=False   ,a__		:     Any=False      ):



    """simple docstring"""




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

    __lowercase          =						[]
    for i in range(image_processor_tester.batch_size      ):
        if equal_resolution:
            __lowercase          =						__lowercase          =						image_processor_tester.max_resolution
        else:
            __lowercase    ,__lowercase          =						np.random.choice(
                np.arange(image_processor_tester.min_resolution   ,image_processor_tester.max_resolution      )   ,2      )
            __lowercase          =						prepare_video(
                image_processor_tester=a__   ,width=a__   ,height=a__   ,numpify=a__   ,torchify=a__   ,)
        video_inputs.append(a__      )

    return video_inputs






class 	SCREAMING_SNAKE_CASE:
       snake_case_			:					Dict   = None

       def    snake_case__      (   self					)   -> List[str]:

           """simple docstring"""



           __lowercase          =						self.image_processing_class(**self.image_processor_dict					)
           __lowercase          =						json.loads(image_processor.to_json_string()					)
           for key, value in self.image_processor_dict.items():
               self.assertEqual(obj[key] ,		lowerCamelCase__					)

       def    snake_case__      (   self					)   -> str:

           """simple docstring"""



           __lowercase          =						self.image_processing_class(**self.image_processor_dict					)

           with tempfile.TemporaryDirectory() as tmpdirname:
               __lowercase          =						os.path.join(lowerCamelCase__ ,		"""image_processor.json"""					)
               image_processor_first.to_json_file(lowerCamelCase__					)
               __lowercase          =						self.image_processing_class.from_json_file(lowerCamelCase__					)

           self.assertEqual(image_processor_second.to_dict() ,		image_processor_first.to_dict()					)

       def    snake_case__      (   self					)   -> str:

           """simple docstring"""



           __lowercase          =						self.image_processing_class(**self.image_processor_dict					)

           with tempfile.TemporaryDirectory() as tmpdirname:
               __lowercase          =						image_processor_first.save_pretrained(lowerCamelCase__					)[0]
               check_json_file_has_correct_format(lowerCamelCase__					)
               __lowercase          =						self.image_processing_class.from_pretrained(lowerCamelCase__					)

           self.assertEqual(image_processor_second.to_dict() ,		image_processor_first.to_dict()					)

       def    snake_case__      (   self					)   -> Any:

           """simple docstring"""



           __lowercase          =						self.image_processing_class()
           self.assertIsNotNone(lowerCamelCase__					)




       @require_torch
       @require_vision
       def    snake_case__      (   self					)   -> int:

           """simple docstring"""



           if self.test_cast_dtype is not None:
               # Initialize image_processor
               __lowercase          =						self.image_processing_class(**self.image_processor_dict					)

               # create random PyTorch tensors
               __lowercase          =						prepare_image_inputs(self.image_processor_tester ,		equal_resolution=lowerCamelCase__ ,		torchify=lowerCamelCase__					)

               __lowercase          =						image_processor(lowerCamelCase__ ,		return_tensors="""pt"""					)
               # for layoutLM compatiblity
               self.assertEqual(encoding.pixel_values.device ,		torch.device("""cpu"""					)					)
               self.assertEqual(encoding.pixel_values.dtype ,		torch.floataa					)

               __lowercase          =						image_processor(lowerCamelCase__ ,		return_tensors="""pt"""					).to(torch.floataa					)
               self.assertEqual(encoding.pixel_values.device ,		torch.device("""cpu"""					)					)
               self.assertEqual(encoding.pixel_values.dtype ,		torch.floataa					)

               __lowercase          =						image_processor(lowerCamelCase__ ,		return_tensors="""pt"""					).to("""cpu""" ,		torch.bfloataa					)
               self.assertEqual(encoding.pixel_values.device ,		torch.device("""cpu"""					)					)
               self.assertEqual(encoding.pixel_values.dtype ,		torch.bfloataa					)

               with self.assertRaises(lowerCamelCase__					):
                   __lowercase          =						image_processor(lowerCamelCase__ ,		return_tensors="""pt"""					).to(torch.bfloataa ,		"""cpu"""					)

               # Try with text + image feature
               __lowercase          =						image_processor(lowerCamelCase__ ,		return_tensors="""pt"""					)
               encoding.update({"""input_ids""": torch.LongTensor([[1, 2, 3], [4, 5, 6]]					)}					)
               __lowercase          =						encoding.to(torch.floataa					)

               self.assertEqual(encoding.pixel_values.device ,		torch.device("""cpu"""					)					)
               self.assertEqual(encoding.pixel_values.dtype ,		torch.floataa					)
               self.assertEqual(encoding.input_ids.dtype ,		torch.long					)










'''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


A							:				Dict			     =	"""Here is a text containing a lot of information: '''{text}'''.

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






class 	SCREAMING_SNAKE_CASE(    __A					):
       snake_case_			:					List[Any]   = """google/flan-t5-base"""
       snake_case_			:					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."""
       )
       snake_case_			:					Optional[int]   = """text_qa"""
       snake_case_			:					List[Any]   = AutoTokenizer
       snake_case_			:					List[str]   = AutoModelForSeqaSeqLM

       snake_case_			:					int   = ["""text""", """text"""]
       snake_case_			:					Dict   = ["""text"""]

       def    snake_case__      (   self ,		lowerCamelCase__ ,		lowerCamelCase__					)   -> Optional[int]:

           """simple docstring"""



           __lowercase          =						QA_PROMPT.format(text=lowerCamelCase__ ,		question=lowerCamelCase__					)
           return self.pre_processor(lowerCamelCase__ ,		return_tensors="""pt"""					)

       def    snake_case__      (   self ,		lowerCamelCase__					)   -> int:

           """simple docstring"""



           __lowercase          =						self.model.generate(**lowerCamelCase__					)

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

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




       def    snake_case__      (   self ,		lowerCamelCase__					)   -> Tuple:

           """simple docstring"""



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




