





'''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				:	Tuple				    =       False


if is_vision_available():
				from PIL import Image
else:



				class 							__UpperCAmelCase  :







						'''simple docstring'''







						@staticmethod
						def        A     (*_lowerCAmelCase						:      int      ,      **_lowerCAmelCase						:      List[Any]      ):
							pass



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







		'''simple docstring'''







		__lowerCAmelCase 				=    MODEL_FOR_VISION_2_SEQ_MAPPING
		__lowerCAmelCase 				=    TF_MODEL_FOR_VISION_2_SEQ_MAPPING







		def        A     (self						:      Any      ,      _lowerCAmelCase						:      Tuple      ,      _lowerCAmelCase						:      Dict      ,      _lowerCAmelCase						:      int      ):
			A							  =      pipeline("""image-to-text"""      ,      model=_lowerCAmelCase      ,      tokenizer=_lowerCAmelCase      ,      image_processor=_lowerCAmelCase      )
			A							  =      [
			    Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""      ),
			    """./tests/fixtures/tests_samples/COCO/000000039769.png""",
			]
			return pipe, examples







		def        A     (self						:      Optional[int]      ,      _lowerCAmelCase						:      str      ,      _lowerCAmelCase						:      int      ):
			A							  =      pipe(_lowerCAmelCase      )
			self.assertEqual(
			    _lowerCAmelCase      ,      [
			        [{"""generated_text""": ANY(_lowerCAmelCase      )}],
			        [{"""generated_text""": ANY(_lowerCAmelCase      )}],
			    ]      ,      )







		@require_tf
		def        A     (self						:      Optional[Any]      ):
			A							  =      pipeline("""image-to-text"""      ,      model="""hf-internal-testing/tiny-random-vit-gpt2"""      ,      framework="""tf"""      )
			A							  =      """./tests/fixtures/tests_samples/COCO/000000039769.png"""

			A							  =      pipe(_lowerCAmelCase      )
			self.assertEqual(
			    _lowerCAmelCase      ,      [
			        {
			            """generated_text""": """growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO"""
			        },
			    ]      ,      )

			A							  =      pipe([image, image]      )
			self.assertEqual(
			    _lowerCAmelCase      ,      [
			        [
			            {
			                """generated_text""": """growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO"""
			            }
			        ],
			        [
			            {
			                """generated_text""": """growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO"""
			            }
			        ],
			    ]      ,      )

			A							  =      pipe(_lowerCAmelCase      ,      max_new_tokens=1      )
			self.assertEqual(
			    _lowerCAmelCase      ,      [{"""generated_text""": """growth"""}]      ,      )







		@require_torch
		def        A     (self						:      Union[str, Any]      ):
			A							  =      pipeline("""image-to-text"""      ,      model="""hf-internal-testing/tiny-random-vit-gpt2"""      )
			A							  =      """./tests/fixtures/tests_samples/COCO/000000039769.png"""

			A							  =      pipe(_lowerCAmelCase      )
			self.assertEqual(
			    _lowerCAmelCase      ,      [
			        {
			            """generated_text""": """growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO"""
			        },
			    ]      ,      )

			A							  =      pipe([image, image]      )
			self.assertEqual(
			    _lowerCAmelCase      ,      [
			        [
			            {
			                """generated_text""": """growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO"""
			            }
			        ],
			        [
			            {
			                """generated_text""": """growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO"""
			            }
			        ],
			    ]      ,      )







		@require_torch
		def        A     (self						:      int      ):
			A							  =      pipeline("""image-to-text"""      ,      model="""hf-internal-testing/tiny-random-BlipForConditionalGeneration"""      )
			A							  =      """./tests/fixtures/tests_samples/COCO/000000039769.png"""
			A							  =      """a photo of"""

			A							  =      pipe(_lowerCAmelCase      ,      prompt=_lowerCAmelCase      )
			self.assertTrue(outputs[0]["""generated_text"""].startswith(_lowerCAmelCase      )      )







		@slow
		@require_torch
		def        A     (self						:      List[Any]      ):
			A							  =      pipeline("""image-to-text"""      ,      model="""ydshieh/vit-gpt2-coco-en"""      )
			A							  =      """./tests/fixtures/tests_samples/COCO/000000039769.png"""

			A							  =      pipe(_lowerCAmelCase      )
			self.assertEqual(_lowerCAmelCase      ,      [{"""generated_text""": """a cat laying on a blanket next to a cat laying on a bed """}]      )

			A							  =      pipe([image, image]      )
			self.assertEqual(
			    _lowerCAmelCase      ,      [
			        [{"""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						:      Optional[Any]      ):
			A							  =      pipeline("""image-to-text"""      ,      model="""Salesforce/blip-image-captioning-base"""      )
			A							  =      """https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/pokemon.png"""
			A							  =      Image.open(requests.get(_lowerCAmelCase      ,      stream=_lowerCAmelCase      ).raw      )

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







		@slow
		@require_torch
		def        A     (self						:      List[str]      ):
			A							  =      pipeline("""image-to-text"""      ,      model="""microsoft/git-base-coco"""      )
			A							  =      """https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/pokemon.png"""
			A							  =      Image.open(requests.get(_lowerCAmelCase      ,      stream=_lowerCAmelCase      ).raw      )

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







		@slow
		@require_torch
		def        A     (self						:      str      ):
			A							  =      pipeline("""image-to-text"""      ,      model="""Salesforce/blip-image-captioning-base"""      )
			A							  =      """https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg"""
			A							  =      Image.open(requests.get(_lowerCAmelCase      ,      stream=_lowerCAmelCase      ).raw      )

			A							  =      """a photography of"""

			A							  =      pipe(_lowerCAmelCase      ,      prompt=_lowerCAmelCase      )
			self.assertEqual(_lowerCAmelCase      ,      [{"""generated_text""": """a photography of a volcano"""}]      )

			with self.assertRaises(_lowerCAmelCase      ):
				A							  =      pipe([image, image]      ,      prompt=[prompt, prompt]      )







		@slow
		@require_torch
		def        A     (self						:      Optional[int]      ):
			A							  =      pipeline("""image-to-text"""      ,      model="""microsoft/git-base-coco"""      )
			A							  =      """https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg"""
			A							  =      Image.open(requests.get(_lowerCAmelCase      ,      stream=_lowerCAmelCase      ).raw      )

			A							  =      """a photo of a"""

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

			with self.assertRaises(_lowerCAmelCase      ):
				A							  =      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						:      Optional[Any]      ):
			A							  =      pipeline("""image-to-text"""      ,      model="""google/pix2struct-ai2d-base"""      )
			A							  =      """https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg"""
			A							  =      Image.open(requests.get(_lowerCAmelCase      ,      stream=_lowerCAmelCase      ).raw      )

			A							  =      """What does the label 15 represent? (1) lava (2) core (3) tunnel (4) ash cloud"""

			A							  =      pipe(_lowerCAmelCase      ,      prompt=_lowerCAmelCase      )
			self.assertEqual(_lowerCAmelCase      ,      [{"""generated_text""": """ash cloud"""}]      )

			with self.assertRaises(_lowerCAmelCase      ):
				A							  =      pipe([image, image]      ,      prompt=[prompt, prompt]      )







		@slow
		@require_tf
		def        A     (self						:      str      ):
			A							  =      pipeline("""image-to-text"""      ,      model="""ydshieh/vit-gpt2-coco-en"""      ,      framework="""tf"""      )
			A							  =      """./tests/fixtures/tests_samples/COCO/000000039769.png"""

			A							  =      pipe(_lowerCAmelCase      )
			self.assertEqual(_lowerCAmelCase      ,      [{"""generated_text""": """a cat laying on a blanket next to a cat laying on a bed """}]      )

			A							  =      pipe([image, image]      )
			self.assertEqual(
			    _lowerCAmelCase      ,      [
			        [{"""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'''


class 							__UpperCAmelCase  :







		'''simple docstring'''







		def __init__(self						:      List[str]      ):
			# numbermap keys are the number and its values are lists of indexes sorted
			# in ascending order
			A							  =      {}
			# indexmap keys are an index and it's values are the number at that index
			A							  =      {}







		def        A     (self						:      Union[str, Any]      ,      _lowerCAmelCase						:      list | str | range      ,      _lowerCAmelCase						:      int      ):
			if isinstance(_lowerCAmelCase      ,      (range, str)      ):
				A							  =      list(_lowerCAmelCase      )
			elif not isinstance(_lowerCAmelCase      ,      _lowerCAmelCase      ):
				raise TypeError(
				    """binary_search_delete() only accepts either a list, range or str"""      )

			A							  =      0
			A							  =      len(_lowerCAmelCase      ) - 1

			while low <= high:
				A							  =      (low + high) // 2
				if array[mid] == item:
					array.pop(_lowerCAmelCase      )
					return array
				elif array[mid] < item:
					A							  =      mid + 1
				else:
					A							  =      mid - 1
			raise ValueError(
			    """Either the item is not in the array or the array was unsorted"""      )







		def        A     (self						:      Dict      ,      _lowerCAmelCase						:      list | str | range      ,      _lowerCAmelCase						:      int      ):
			if isinstance(_lowerCAmelCase      ,      (range, str)      ):
				A							  =      list(_lowerCAmelCase      )
			elif not isinstance(_lowerCAmelCase      ,      _lowerCAmelCase      ):
				raise TypeError(
				    """binary_search_insert() only accepts either a list, range or str"""      )

			A							  =      0
			A							  =      len(_lowerCAmelCase      ) - 1

			while low <= high:
				A							  =      (low + high) // 2
				if array[mid] == index:
					# If the item already exists in the array,
					# insert it after the existing item
					array.insert(mid + 1      ,      _lowerCAmelCase      )
					return array
				elif array[mid] < index:
					A							  =      mid + 1
				else:
					A							  =      mid - 1

        # If the item doesn't exist in the array, insert it at the appropriate position
			array.insert(_lowerCAmelCase      ,      _lowerCAmelCase      )
			return array







		def        A     (self						:      List[str]      ,      _lowerCAmelCase						:      int      ,      _lowerCAmelCase						:      int      ):
			# Remove previous index
			if index in self.indexmap:
				A							  =      self.indexmap[index]
				if len(self.numbermap[n]      ) == 1:
					del self.numbermap[n]
				else:
					A							  =      self.binary_search_delete(self.numbermap[n]      ,      _lowerCAmelCase      )

        # Set new index
			A							  =      number

			# Number not seen before or empty so insert number value
			if number not in self.numbermap:
				A							  =      [index]

			# Here we need to perform a binary search insertion in order to insert
			# The item in the correct place
			else:
				A							  =      self.binary_search_insert(
				    self.numbermap[number]      ,      _lowerCAmelCase      )







		def        A     (self						:      int      ,      _lowerCAmelCase						:      int      ):
			return self.numbermap.get(_lowerCAmelCase      ,      [-1]      )[0]


if __name__ == "__main__":
				import doctest

				doctest.testmod()

