



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 DeiTImageProcessor


class 	snake_case_			(unittest.TestCase	):




       """simple docstring"""






       def __init__(  self  ,lowercase  ,lowercase=7  ,lowercase=3  ,lowercase=18  ,lowercase=30  ,lowercase=400  ,lowercase=True  ,lowercase=None  ,lowercase=True  ,lowercase=None  ,lowercase=True  ,lowercase=[0.5, 0.5, 0.5]  ,lowercase=[0.5, 0.5, 0.5]  ,):

             """simple docstring"""





             UpperCAmelCase_	:						Optional[int]					   =		size if size is not None else {"height": 20, "width": 20}
             UpperCAmelCase_	:						List[str]					   =		crop_size if crop_size is not None else {"height": 18, "width": 18}

             UpperCAmelCase_	:						int					   =		parent
             UpperCAmelCase_	:						Dict					   =		batch_size
             UpperCAmelCase_	:						List[str]					   =		num_channels
             UpperCAmelCase_	:						List[Any]					   =		image_size
             UpperCAmelCase_	:						List[str]					   =		min_resolution
             UpperCAmelCase_	:						List[Any]					   =		max_resolution
             UpperCAmelCase_	:						List[str]					   =		do_resize
             UpperCAmelCase_	:						List[str]					   =		size
             UpperCAmelCase_	:						List[str]					   =		do_center_crop
             UpperCAmelCase_	:						List[Any]					   =		crop_size
             UpperCAmelCase_	:						str					   =		do_normalize
             UpperCAmelCase_	:						Tuple					   =		image_mean
             UpperCAmelCase_	:						Any					   =		image_std



       def 			A_ (  self):

             """simple docstring"""





             return {
                 "do_resize": self.do_resize,
                 "size": self.size,
                 "do_center_crop": self.do_center_crop,
                 "crop_size": self.crop_size,
                 "do_normalize": self.do_normalize,
                 "image_mean": self.image_mean,
                 "image_std": self.image_std,
             }


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




       """simple docstring"""






       _lowerCamelCase           =					DeiTImageProcessor if is_vision_available() else None
       _lowerCamelCase           =					True



       def 			A_ (  self):

             """simple docstring"""





             UpperCAmelCase_	:						int					   =		DeiTImageProcessingTester(self)



       @property
       def 			A_ (  self):

             """simple docstring"""





             return self.image_processor_tester.prepare_image_processor_dict()



       def 			A_ (  self):

             """simple docstring"""





             UpperCAmelCase_	:						Optional[int]					   =		self.image_processing_class(**self.image_processor_dict)
             self.assertTrue(hasattr(lowercase  ,"do_resize"))
             self.assertTrue(hasattr(lowercase  ,"size"))
             self.assertTrue(hasattr(lowercase  ,"do_center_crop"))
             self.assertTrue(hasattr(lowercase  ,"center_crop"))
             self.assertTrue(hasattr(lowercase  ,"do_normalize"))
             self.assertTrue(hasattr(lowercase  ,"image_mean"))
             self.assertTrue(hasattr(lowercase  ,"image_std"))



       def 			A_ (  self):

             """simple docstring"""





             UpperCAmelCase_	:						Optional[int]					   =		self.image_processing_class.from_dict(self.image_processor_dict)
             self.assertEqual(image_processor.size  ,{"height": 20, "width": 20})
             self.assertEqual(image_processor.crop_size  ,{"height": 18, "width": 18})

             UpperCAmelCase_	:						Optional[Any]					   =		self.image_processing_class.from_dict(self.image_processor_dict  ,size=42  ,crop_size=84)
             self.assertEqual(image_processor.size  ,{"height": 42, "width": 42})
             self.assertEqual(image_processor.crop_size  ,{"height": 84, "width": 84})



       def 			A_ (  self):

             """simple docstring"""





             pass



       def 			A_ (  self):

             """simple docstring"""





             UpperCAmelCase_	:						List[str]					   =		self.image_processing_class(**self.image_processor_dict)
             # create random PIL images
             UpperCAmelCase_	:						Tuple					   =		prepare_image_inputs(self.image_processor_tester  ,equal_resolution=lowercase)
             for image in image_inputs:
                   self.assertIsInstance(lowercase  ,Image.Image)

             # Test not batched input
             UpperCAmelCase_	:						Union[str, Any]					   =		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.crop_size["height"],
                     self.image_processor_tester.crop_size["width"],
                 )  ,)

             # Test batched
             UpperCAmelCase_	:						Union[str, Any]					   =		image_processing(lowercase  ,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.crop_size["height"],
                     self.image_processor_tester.crop_size["width"],
                 )  ,)



       def 			A_ (  self):

             """simple docstring"""





             UpperCAmelCase_	:						Union[str, Any]					   =		self.image_processing_class(**self.image_processor_dict)
             # create random numpy tensors
             UpperCAmelCase_	:						str					   =		prepare_image_inputs(self.image_processor_tester  ,equal_resolution=lowercase  ,numpify=lowercase)
             for image in image_inputs:
                   self.assertIsInstance(lowercase  ,np.ndarray)

             # Test not batched input
             UpperCAmelCase_	:						int					   =		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.crop_size["height"],
                     self.image_processor_tester.crop_size["width"],
                 )  ,)

             # Test batched
             UpperCAmelCase_	:						str					   =		image_processing(lowercase  ,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.crop_size["height"],
                     self.image_processor_tester.crop_size["width"],
                 )  ,)



       def 			A_ (  self):

             """simple docstring"""





             UpperCAmelCase_	:						Union[str, Any]					   =		self.image_processing_class(**self.image_processor_dict)
             # create random PyTorch tensors
             UpperCAmelCase_	:						Dict					   =		prepare_image_inputs(self.image_processor_tester  ,equal_resolution=lowercase  ,torchify=lowercase)
             for image in image_inputs:
                   self.assertIsInstance(lowercase  ,torch.Tensor)

             # Test not batched input
             UpperCAmelCase_	:						Optional[int]					   =		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.crop_size["height"],
                     self.image_processor_tester.crop_size["width"],
                 )  ,)

             # Test batched
             UpperCAmelCase_	:						Union[str, Any]					   =		image_processing(lowercase  ,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.crop_size["height"],
                     self.image_processor_tester.crop_size["width"],
                 )  ,)





import unittest

import requests

from transformers import MODEL_FOR_VISION_2_SEQ_MAPPING, TF_MODEL_FOR_VISION_2_SEQ_MAPPING, is_vision_available
from transformers.pipelines import pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    is_torch_available,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_torch_available():
   from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11
else:
   __lowerCamelCase								=      False


if is_vision_available():
   from PIL import Image
else:


   class 	snake_case_			:




          """simple docstring"""






          @staticmethod
          def 			A_ (  *lowercase  ,**lowercase):

                """simple docstring"""





                pass


@is_pipeline_test
@require_vision
class 	snake_case_			(unittest.TestCase	):




       """simple docstring"""






       _lowerCamelCase           =					MODEL_FOR_VISION_2_SEQ_MAPPING
       _lowerCamelCase           =					TF_MODEL_FOR_VISION_2_SEQ_MAPPING



       def 			A_ (  self  ,lowercase  ,lowercase  ,lowercase):

             """simple docstring"""





             UpperCAmelCase_	:						Optional[Any]					   =		pipeline("image-to-text"  ,model=lowercase  ,tokenizer=lowercase  ,image_processor=lowercase)
             UpperCAmelCase_	:						Any					   =		[
                 Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"),
                 "./tests/fixtures/tests_samples/COCO/000000039769.png",
             ]
             return pipe, examples



       def 			A_ (  self  ,lowercase  ,lowercase):

             """simple docstring"""





             UpperCAmelCase_	:						str					   =		pipe(lowercase)
             self.assertEqual(
                 lowercase  ,[
                     [{"generated_text": ANY(lowercase)}],
                     [{"generated_text": ANY(lowercase)}],
                 ]  ,)



       @require_tf
       def 			A_ (  self):

             """simple docstring"""





             UpperCAmelCase_	:						str					   =		pipeline("image-to-text"  ,model="hf-internal-testing/tiny-random-vit-gpt2"  ,framework="tf")
             UpperCAmelCase_	:						int					   =		"./tests/fixtures/tests_samples/COCO/000000039769.png"

             UpperCAmelCase_	:						Tuple					   =		pipe(lowercase)
             self.assertEqual(
                 lowercase  ,[
                     {
                         "generated_text": "growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO"
                     },
                 ]  ,)

             UpperCAmelCase_	:						Optional[int]					   =		pipe([image, image])
             self.assertEqual(
                 lowercase  ,[
                     [
                         {
                             "generated_text": "growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO"
                         }
                     ],
                     [
                         {
                             "generated_text": "growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO"
                         }
                     ],
                 ]  ,)

             UpperCAmelCase_	:						Any					   =		pipe(lowercase  ,max_new_tokens=1)
             self.assertEqual(
                 lowercase  ,[{"generated_text": "growth"}]  ,)



       @require_torch
       def 			A_ (  self):

             """simple docstring"""





             UpperCAmelCase_	:						List[Any]					   =		pipeline("image-to-text"  ,model="hf-internal-testing/tiny-random-vit-gpt2")
             UpperCAmelCase_	:						str					   =		"./tests/fixtures/tests_samples/COCO/000000039769.png"

             UpperCAmelCase_	:						str					   =		pipe(lowercase)
             self.assertEqual(
                 lowercase  ,[
                     {
                         "generated_text": "growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO"
                     },
                 ]  ,)

             UpperCAmelCase_	:						Optional[int]					   =		pipe([image, image])
             self.assertEqual(
                 lowercase  ,[
                     [
                         {
                             "generated_text": "growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO"
                         }
                     ],
                     [
                         {
                             "generated_text": "growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO"
                         }
                     ],
                 ]  ,)



       @require_torch
       def 			A_ (  self):

             """simple docstring"""





             UpperCAmelCase_	:						List[Any]					   =		pipeline("image-to-text"  ,model="hf-internal-testing/tiny-random-BlipForConditionalGeneration")
             UpperCAmelCase_	:						Union[str, Any]					   =		"./tests/fixtures/tests_samples/COCO/000000039769.png"
             UpperCAmelCase_	:						Optional[Any]					   =		"a photo of"

             UpperCAmelCase_	:						Any					   =		pipe(lowercase  ,prompt=lowercase)
             self.assertTrue(outputs[0]["generated_text"].startswith(lowercase))



       @slow
       @require_torch
       def 			A_ (  self):

             """simple docstring"""





             UpperCAmelCase_	:						List[Any]					   =		pipeline("image-to-text"  ,model="ydshieh/vit-gpt2-coco-en")
             UpperCAmelCase_	:						List[str]					   =		"./tests/fixtures/tests_samples/COCO/000000039769.png"

             UpperCAmelCase_	:						List[str]					   =		pipe(lowercase)
             self.assertEqual(lowercase  ,[{"generated_text": "a cat laying on a blanket next to a cat laying on a bed "}])

             UpperCAmelCase_	:						Optional[Any]					   =		pipe([image, image])
             self.assertEqual(
                 lowercase  ,[
                     [{"generated_text": "a cat laying on a blanket next to a cat laying on a bed "}],
                     [{"generated_text": "a cat laying on a blanket next to a cat laying on a bed "}],
                 ]  ,)



       @slow
       @require_torch
       def 			A_ (  self):

             """simple docstring"""





             UpperCAmelCase_	:						Any					   =		pipeline("image-to-text"  ,model="Salesforce/blip-image-captioning-base")
             UpperCAmelCase_	:						str					   =		"https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/pokemon.png"
             UpperCAmelCase_	:						Optional[Any]					   =		Image.open(requests.get(lowercase  ,stream=lowercase).raw)

             UpperCAmelCase_	:						Any					   =		pipe(lowercase)
             self.assertEqual(lowercase  ,[{"generated_text": "a pink pokemon pokemon with a blue shirt and a blue shirt"}])



       @slow
       @require_torch
       def 			A_ (  self):

             """simple docstring"""





             UpperCAmelCase_	:						str					   =		pipeline("image-to-text"  ,model="microsoft/git-base-coco")
             UpperCAmelCase_	:						Union[str, Any]					   =		"https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/pokemon.png"
             UpperCAmelCase_	:						int					   =		Image.open(requests.get(lowercase  ,stream=lowercase).raw)

             UpperCAmelCase_	:						Tuple					   =		pipe(lowercase)
             self.assertEqual(lowercase  ,[{"generated_text": "a cartoon of a purple character."}])



       @slow
       @require_torch
       def 			A_ (  self):

             """simple docstring"""





             UpperCAmelCase_	:						Any					   =		pipeline("image-to-text"  ,model="Salesforce/blip-image-captioning-base")
             UpperCAmelCase_	:						Union[str, Any]					   =		"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg"
             UpperCAmelCase_	:						int					   =		Image.open(requests.get(lowercase  ,stream=lowercase).raw)

             UpperCAmelCase_	:						Any					   =		"a photography of"

             UpperCAmelCase_	:						Optional[Any]					   =		pipe(lowercase  ,prompt=lowercase)
             self.assertEqual(lowercase  ,[{"generated_text": "a photography of a volcano"}])

             with self.assertRaises(lowercase):
                   UpperCAmelCase_	:						Tuple					   =		pipe([image, image]  ,prompt=[prompt, prompt])



       @slow
       @require_torch
       def 			A_ (  self):

             """simple docstring"""





             UpperCAmelCase_	:						Optional[int]					   =		pipeline("image-to-text"  ,model="microsoft/git-base-coco")
             UpperCAmelCase_	:						List[str]					   =		"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg"
             UpperCAmelCase_	:						List[str]					   =		Image.open(requests.get(lowercase  ,stream=lowercase).raw)

             UpperCAmelCase_	:						Optional[Any]					   =		"a photo of a"

             UpperCAmelCase_	:						Tuple					   =		pipe(lowercase  ,prompt=lowercase)
             self.assertEqual(lowercase  ,[{"generated_text": "a photo of a tent with a tent and a tent in the background."}])

             with self.assertRaises(lowercase):
                   UpperCAmelCase_	:						Tuple					   =		pipe([image, image]  ,prompt=[prompt, prompt])



       @unittest.skipIf(
           not is_torch_greater_or_equal_than_1_11  ,reason="`Pix2StructImageProcessor` requires `torch>=1.11.0`.")
       @slow
       @require_torch
       def 			A_ (  self):

             """simple docstring"""





             UpperCAmelCase_	:						Optional[int]					   =		pipeline("image-to-text"  ,model="google/pix2struct-ai2d-base")
             UpperCAmelCase_	:						Any					   =		"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg"
             UpperCAmelCase_	:						Union[str, Any]					   =		Image.open(requests.get(lowercase  ,stream=lowercase).raw)

             UpperCAmelCase_	:						List[Any]					   =		"What does the label 15 represent? (1) lava (2) core (3) tunnel (4) ash cloud"

             UpperCAmelCase_	:						Dict					   =		pipe(lowercase  ,prompt=lowercase)
             self.assertEqual(lowercase  ,[{"generated_text": "ash cloud"}])

             with self.assertRaises(lowercase):
                   UpperCAmelCase_	:						List[str]					   =		pipe([image, image]  ,prompt=[prompt, prompt])



       @slow
       @require_tf
       def 			A_ (  self):

             """simple docstring"""





             UpperCAmelCase_	:						Union[str, Any]					   =		pipeline("image-to-text"  ,model="ydshieh/vit-gpt2-coco-en"  ,framework="tf")
             UpperCAmelCase_	:						str					   =		"./tests/fixtures/tests_samples/COCO/000000039769.png"

             UpperCAmelCase_	:						Union[str, Any]					   =		pipe(lowercase)
             self.assertEqual(lowercase  ,[{"generated_text": "a cat laying on a blanket next to a cat laying on a bed "}])

             UpperCAmelCase_	:						int					   =		pipe([image, image])
             self.assertEqual(
                 lowercase  ,[
                     [{"generated_text": "a cat laying on a blanket next to a cat laying on a bed "}],
                     [{"generated_text": "a cat laying on a blanket next to a cat laying on a bed "}],
                 ]  ,)
