





"""simple docstring"""




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_					:						List[str]      = False


if is_vision_available():
   from PIL import Image
else:

   class 			_UpperCAmelCase  :



         '''simple docstring'''

         @staticmethod
         def  lowerCamelCase_      (					*snake_case_ ,				**snake_case_  ):

           """simple docstring"""

           pass

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



      '''simple docstring'''
      lowercase_				:			Union[str, Any]        =       MODEL_FOR_VISION_2_SEQ_MAPPING
      lowercase_				:			List[str]        =       TF_MODEL_FOR_VISION_2_SEQ_MAPPING

      def  lowerCamelCase_      (					self ,				snake_case_ ,				snake_case_ ,				snake_case_  ):

        """simple docstring"""

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

      def  lowerCamelCase_      (					self ,				snake_case_ ,				snake_case_  ):

        """simple docstring"""

        A_  :	List[str]    						=  pipe(snake_case_  )
        self.assertEqual(
            snake_case_ ,				[
                [{'generated_text': ANY(snake_case_  )}],
                [{'generated_text': ANY(snake_case_  )}],
            ] ,				)

      @require_tf
      def  lowerCamelCase_      (					self  ):

        """simple docstring"""

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

        A_  :	List[Any]    						=  pipe(snake_case_  )
        self.assertEqual(
            snake_case_ ,				[
                {
                    'generated_text': 'growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO'
                },
            ] ,				)

        A_  :	List[Any]    						=  pipe([image, image]  )
        self.assertEqual(
            snake_case_ ,				[
                [
                    {
                        'generated_text': 'growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO'
                    }
                ],
                [
                    {
                        'generated_text': 'growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO'
                    }
                ],
            ] ,				)

        A_  :	Union[str, Any]    						=  pipe(snake_case_ ,				max_new_tokens=1  )
        self.assertEqual(
            snake_case_ ,				[{'generated_text': 'growth'}] ,				)

      @require_torch
      def  lowerCamelCase_      (					self  ):

        """simple docstring"""

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

        A_  :	Optional[int]    						=  pipe(snake_case_  )
        self.assertEqual(
            snake_case_ ,				[
                {
                    'generated_text': 'growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO'
                },
            ] ,				)

        A_  :	List[str]    						=  pipe([image, image]  )
        self.assertEqual(
            snake_case_ ,				[
                [
                    {
                        'generated_text': 'growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO'
                    }
                ],
                [
                    {
                        'generated_text': 'growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO'
                    }
                ],
            ] ,				)

      @require_torch
      def  lowerCamelCase_      (					self  ):

        """simple docstring"""

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

        A_  :	str    						=  pipe(snake_case_ ,				prompt=snake_case_  )
        self.assertTrue(outputs[0]['generated_text'].startswith(snake_case_  )  )

      @slow
      @require_torch
      def  lowerCamelCase_      (					self  ):

        """simple docstring"""

        A_  :	Any    						=  pipeline('image-to-text' ,				model='ydshieh/vit-gpt2-coco-en'  )
        A_  :	Any    						=  './tests/fixtures/tests_samples/COCO/000000039769.png'

        A_  :	str    						=  pipe(snake_case_  )
        self.assertEqual(snake_case_ ,				[{'generated_text': 'a cat laying on a blanket next to a cat laying on a bed '}]  )

        A_  :	Any    						=  pipe([image, image]  )
        self.assertEqual(
            snake_case_ ,				[
                [{'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  lowerCamelCase_      (					self  ):

        """simple docstring"""

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

        A_  :	Optional[int]    						=  pipe(snake_case_  )
        self.assertEqual(snake_case_ ,				[{'generated_text': 'a pink pokemon pokemon with a blue shirt and a blue shirt'}]  )

      @slow
      @require_torch
      def  lowerCamelCase_      (					self  ):

        """simple docstring"""

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

        A_  :	Optional[int]    						=  pipe(snake_case_  )
        self.assertEqual(snake_case_ ,				[{'generated_text': 'a cartoon of a purple character.'}]  )

      @slow
      @require_torch
      def  lowerCamelCase_      (					self  ):

        """simple docstring"""

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

        A_  :	List[Any]    						=  'a photography of'

        A_  :	Tuple    						=  pipe(snake_case_ ,				prompt=snake_case_  )
        self.assertEqual(snake_case_ ,				[{'generated_text': 'a photography of a volcano'}]  )

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

      @slow
      @require_torch
      def  lowerCamelCase_      (					self  ):

        """simple docstring"""

        A_  :	Tuple    						=  pipeline('image-to-text' ,				model='microsoft/git-base-coco'  )
        A_  :	Tuple    						=  'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg'
        A_  :	Tuple    						=  Image.open(requests.get(snake_case_ ,				stream=snake_case_  ).raw  )

        A_  :	Dict    						=  'a photo of a'

        A_  :	Optional[int]    						=  pipe(snake_case_ ,				prompt=snake_case_  )
        self.assertEqual(snake_case_ ,				[{'generated_text': 'a photo of a tent with a tent and a tent in the background.'}]  )

        with self.assertRaises(snake_case_  ):
          A_  :	List[str]    						=  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  lowerCamelCase_      (					self  ):

        """simple docstring"""

        A_  :	Any    						=  pipeline('image-to-text' ,				model='google/pix2struct-ai2d-base'  )
        A_  :	Any    						=  'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg'
        A_  :	Dict    						=  Image.open(requests.get(snake_case_ ,				stream=snake_case_  ).raw  )

        A_  :	int    						=  'What does the label 15 represent? (1) lava (2) core (3) tunnel (4) ash cloud'

        A_  :	Optional[Any]    						=  pipe(snake_case_ ,				prompt=snake_case_  )
        self.assertEqual(snake_case_ ,				[{'generated_text': 'ash cloud'}]  )

        with self.assertRaises(snake_case_  ):
          A_  :	Tuple    						=  pipe([image, image] ,				prompt=[prompt, prompt]  )

      @slow
      @require_tf
      def  lowerCamelCase_      (					self  ):

        """simple docstring"""

        A_  :	Optional[int]    						=  pipeline('image-to-text' ,				model='ydshieh/vit-gpt2-coco-en' ,				framework='tf'  )
        A_  :	Optional[int]    						=  './tests/fixtures/tests_samples/COCO/000000039769.png'

        A_  :	Optional[int]    						=  pipe(snake_case_  )
        self.assertEqual(snake_case_ ,				[{'generated_text': 'a cat laying on a blanket next to a cat laying on a bed '}]  )

        A_  :	List[Any]    						=  pipe([image, image]  )
        self.assertEqual(
            snake_case_ ,				[
                [{'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 '}],
            ] ,				)






"""simple docstring"""




from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


lowerCamelCase_					:						List[str]      = logging.get_logger(__name__)

lowerCamelCase_					:						Optional[int]      = {
    'google/electra-small-generator': 'https://huggingface.co/google/electra-small-generator/resolve/main/config.json',
    'google/electra-base-generator': 'https://huggingface.co/google/electra-base-generator/resolve/main/config.json',
    'google/electra-large-generator': 'https://huggingface.co/google/electra-large-generator/resolve/main/config.json',
    'google/electra-small-discriminator': (
        'https://huggingface.co/google/electra-small-discriminator/resolve/main/config.json'
    ),
    'google/electra-base-discriminator': (
        'https://huggingface.co/google/electra-base-discriminator/resolve/main/config.json'
    ),
    'google/electra-large-discriminator': (
        'https://huggingface.co/google/electra-large-discriminator/resolve/main/config.json'
    ),
}

class 			_UpperCAmelCase  (       UpperCAmelCase__		):



      '''simple docstring'''
      lowercase_				:			Tuple        =       """electra"""

      def __init__(					self ,				snake_case_=3_0_5_2_2 ,				snake_case_=1_2_8 ,				snake_case_=2_5_6 ,				snake_case_=1_2 ,				snake_case_=4 ,				snake_case_=1_0_2_4 ,				snake_case_="gelu" ,				snake_case_=0.1 ,				snake_case_=0.1 ,				snake_case_=5_1_2 ,				snake_case_=2 ,				snake_case_=0.02 ,				snake_case_=1E-12 ,				snake_case_="first" ,				snake_case_=True ,				snake_case_="gelu" ,				snake_case_=0.1 ,				snake_case_=0 ,				snake_case_="absolute" ,				snake_case_=True ,				snake_case_=None ,				**snake_case_ ,				):

        """simple docstring"""

        super().__init__(pad_token_id=snake_case_ ,				**snake_case_  )

        A_  :	Optional[Any]    						=  vocab_size
        A_  :	Any    						=  embedding_size
        A_  :	Optional[int]    						=  hidden_size
        A_  :	Tuple    						=  num_hidden_layers
        A_  :	Tuple    						=  num_attention_heads
        A_  :	List[Any]    						=  intermediate_size
        A_  :	Any    						=  hidden_act
        A_  :	str    						=  hidden_dropout_prob
        A_  :	Any    						=  attention_probs_dropout_prob
        A_  :	str    						=  max_position_embeddings
        A_  :	Optional[Any]    						=  type_vocab_size
        A_  :	Dict    						=  initializer_range
        A_  :	Optional[int]    						=  layer_norm_eps

        A_  :	int    						=  summary_type
        A_  :	List[str]    						=  summary_use_proj
        A_  :	Optional[Any]    						=  summary_activation
        A_  :	Optional[Any]    						=  summary_last_dropout
        A_  :	List[Any]    						=  position_embedding_type
        A_  :	Union[str, Any]    						=  use_cache
        A_  :	Tuple    						=  classifier_dropout


class 			_UpperCAmelCase  (       UpperCAmelCase__		):



      '''simple docstring'''

      @property
      def  lowerCamelCase_      (					self  ):

        """simple docstring"""

        if self.task == "multiple-choice":
          A_  :	int    						=  {0: 'batch', 1: 'choice', 2: 'sequence'}
        else:
          A_  :	Optional[Any]    						=  {0: 'batch', 1: 'sequence'}
        return OrderedDict(
            [
                ('input_ids', dynamic_axis),
                ('attention_mask', dynamic_axis),
                ('token_type_ids', dynamic_axis),
            ]  )