





"""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 typing import TYPE_CHECKING

from ..utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available


lowerCamelCase_					:						Any      = {
    'configuration_utils': ['GenerationConfig'],
    'streamers': ['TextIteratorStreamer', 'TextStreamer'],
}

try:
   if not is_torch_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   lowerCamelCase_					:						Optional[Any]      = [
       'Constraint',
       'ConstraintListState',
       'DisjunctiveConstraint',
       'PhrasalConstraint',
   ]
   lowerCamelCase_					:						List[str]      = [
       'BeamHypotheses',
       'BeamScorer',
       'BeamSearchScorer',
       'ConstrainedBeamSearchScorer',
   ]
   lowerCamelCase_					:						Dict      = [
       'EpsilonLogitsWarper',
       'EtaLogitsWarper',
       'ForcedBOSTokenLogitsProcessor',
       'ForcedEOSTokenLogitsProcessor',
       'HammingDiversityLogitsProcessor',
       'InfNanRemoveLogitsProcessor',
       'LogitsProcessor',
       'LogitsProcessorList',
       'LogitsWarper',
       'MinLengthLogitsProcessor',
       'MinNewTokensLengthLogitsProcessor',
       'NoBadWordsLogitsProcessor',
       'NoRepeatNGramLogitsProcessor',
       'PrefixConstrainedLogitsProcessor',
       'RepetitionPenaltyLogitsProcessor',
       'SequenceBiasLogitsProcessor',
       'EncoderRepetitionPenaltyLogitsProcessor',
       'TemperatureLogitsWarper',
       'TopKLogitsWarper',
       'TopPLogitsWarper',
       'TypicalLogitsWarper',
       'EncoderNoRepeatNGramLogitsProcessor',
       'ExponentialDecayLengthPenalty',
       'LogitNormalization',
   ]
   lowerCamelCase_					:						str      = [
       'MaxNewTokensCriteria',
       'MaxLengthCriteria',
       'MaxTimeCriteria',
       'StoppingCriteria',
       'StoppingCriteriaList',
       'validate_stopping_criteria',
   ]
   lowerCamelCase_					:						List[str]      = [
       'GenerationMixin',
       'top_k_top_p_filtering',
       'GreedySearchEncoderDecoderOutput',
       'GreedySearchDecoderOnlyOutput',
       'SampleEncoderDecoderOutput',
       'SampleDecoderOnlyOutput',
       'BeamSearchEncoderDecoderOutput',
       'BeamSearchDecoderOnlyOutput',
       'BeamSampleEncoderDecoderOutput',
       'BeamSampleDecoderOnlyOutput',
       'ContrastiveSearchEncoderDecoderOutput',
       'ContrastiveSearchDecoderOnlyOutput',
   ]

try:
   if not is_tf_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   lowerCamelCase_					:						Union[str, Any]      = [
       'TFForcedBOSTokenLogitsProcessor',
       'TFForcedEOSTokenLogitsProcessor',
       'TFLogitsProcessor',
       'TFLogitsProcessorList',
       'TFLogitsWarper',
       'TFMinLengthLogitsProcessor',
       'TFNoBadWordsLogitsProcessor',
       'TFNoRepeatNGramLogitsProcessor',
       'TFRepetitionPenaltyLogitsProcessor',
       'TFTemperatureLogitsWarper',
       'TFTopKLogitsWarper',
       'TFTopPLogitsWarper',
       'TFForceTokensLogitsProcessor',
       'TFSuppressTokensAtBeginLogitsProcessor',
       'TFSuppressTokensLogitsProcessor',
   ]
   lowerCamelCase_					:						Union[str, Any]      = [
       'TFGenerationMixin',
       'tf_top_k_top_p_filtering',
       'TFGreedySearchDecoderOnlyOutput',
       'TFGreedySearchEncoderDecoderOutput',
       'TFSampleEncoderDecoderOutput',
       'TFSampleDecoderOnlyOutput',
       'TFBeamSearchEncoderDecoderOutput',
       'TFBeamSearchDecoderOnlyOutput',
       'TFBeamSampleEncoderDecoderOutput',
       'TFBeamSampleDecoderOnlyOutput',
       'TFContrastiveSearchEncoderDecoderOutput',
       'TFContrastiveSearchDecoderOnlyOutput',
   ]

try:
   if not is_flax_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   lowerCamelCase_					:						int      = [
       'FlaxForcedBOSTokenLogitsProcessor',
       'FlaxForcedEOSTokenLogitsProcessor',
       'FlaxLogitsProcessor',
       'FlaxLogitsProcessorList',
       'FlaxLogitsWarper',
       'FlaxMinLengthLogitsProcessor',
       'FlaxTemperatureLogitsWarper',
       'FlaxTopKLogitsWarper',
       'FlaxTopPLogitsWarper',
   ]
   lowerCamelCase_					:						Tuple      = [
       'FlaxGenerationMixin',
       'FlaxGreedySearchOutput',
       'FlaxSampleOutput',
       'FlaxBeamSearchOutput',
   ]

if TYPE_CHECKING:
   from .configuration_utils import GenerationConfig
   from .streamers import TextIteratorStreamer, TextStreamer

   try:
      if not is_torch_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .beam_constraints import Constraint, ConstraintListState, DisjunctiveConstraint, PhrasalConstraint
      from .beam_search import BeamHypotheses, BeamScorer, BeamSearchScorer, ConstrainedBeamSearchScorer
      from .logits_process import (
          EncoderNoRepeatNGramLogitsProcessor,
          EncoderRepetitionPenaltyLogitsProcessor,
          EpsilonLogitsWarper,
          EtaLogitsWarper,
          ExponentialDecayLengthPenalty,
          ForcedBOSTokenLogitsProcessor,
          ForcedEOSTokenLogitsProcessor,
          HammingDiversityLogitsProcessor,
          InfNanRemoveLogitsProcessor,
          LogitNormalization,
          LogitsProcessor,
          LogitsProcessorList,
          LogitsWarper,
          MinLengthLogitsProcessor,
          MinNewTokensLengthLogitsProcessor,
          NoBadWordsLogitsProcessor,
          NoRepeatNGramLogitsProcessor,
          PrefixConstrainedLogitsProcessor,
          RepetitionPenaltyLogitsProcessor,
          SequenceBiasLogitsProcessor,
          TemperatureLogitsWarper,
          TopKLogitsWarper,
          TopPLogitsWarper,
          TypicalLogitsWarper,
      )
      from .stopping_criteria import (
          MaxLengthCriteria,
          MaxNewTokensCriteria,
          MaxTimeCriteria,
          StoppingCriteria,
          StoppingCriteriaList,
          validate_stopping_criteria,
      )
      from .utils import (
          BeamSampleDecoderOnlyOutput,
          BeamSampleEncoderDecoderOutput,
          BeamSearchDecoderOnlyOutput,
          BeamSearchEncoderDecoderOutput,
          ContrastiveSearchDecoderOnlyOutput,
          ContrastiveSearchEncoderDecoderOutput,
          GenerationMixin,
          GreedySearchDecoderOnlyOutput,
          GreedySearchEncoderDecoderOutput,
          SampleDecoderOnlyOutput,
          SampleEncoderDecoderOutput,
          top_k_top_p_filtering,
      )

   try:
      if not is_tf_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .tf_logits_process import (
          TFForcedBOSTokenLogitsProcessor,
          TFForcedEOSTokenLogitsProcessor,
          TFForceTokensLogitsProcessor,
          TFLogitsProcessor,
          TFLogitsProcessorList,
          TFLogitsWarper,
          TFMinLengthLogitsProcessor,
          TFNoBadWordsLogitsProcessor,
          TFNoRepeatNGramLogitsProcessor,
          TFRepetitionPenaltyLogitsProcessor,
          TFSuppressTokensAtBeginLogitsProcessor,
          TFSuppressTokensLogitsProcessor,
          TFTemperatureLogitsWarper,
          TFTopKLogitsWarper,
          TFTopPLogitsWarper,
      )
      from .tf_utils import (
          TFBeamSampleDecoderOnlyOutput,
          TFBeamSampleEncoderDecoderOutput,
          TFBeamSearchDecoderOnlyOutput,
          TFBeamSearchEncoderDecoderOutput,
          TFContrastiveSearchDecoderOnlyOutput,
          TFContrastiveSearchEncoderDecoderOutput,
          TFGenerationMixin,
          TFGreedySearchDecoderOnlyOutput,
          TFGreedySearchEncoderDecoderOutput,
          TFSampleDecoderOnlyOutput,
          TFSampleEncoderDecoderOutput,
          tf_top_k_top_p_filtering,
      )

   try:
      if not is_flax_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .flax_logits_process import (
          FlaxForcedBOSTokenLogitsProcessor,
          FlaxForcedEOSTokenLogitsProcessor,
          FlaxLogitsProcessor,
          FlaxLogitsProcessorList,
          FlaxLogitsWarper,
          FlaxMinLengthLogitsProcessor,
          FlaxTemperatureLogitsWarper,
          FlaxTopKLogitsWarper,
          FlaxTopPLogitsWarper,
      )
      from .flax_utils import FlaxBeamSearchOutput, FlaxGenerationMixin, FlaxGreedySearchOutput, FlaxSampleOutput
else:
   import sys

   lowerCamelCase_					:						Tuple      = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)