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


if is_vision_available():
 from PIL import Image
else:


 class  UpperCamelCase__  :






  @staticmethod
  def 	lowercase_						(			*_A  :Optional[Any]	,				**_A  :List[str]			)				->			Optional[Any]:







        '''simple docstring'''



        pass


@is_pipeline_test
@require_vision
class  UpperCamelCase__  (    unittest.TestCase):
 UpperCAmelCase__    :    str										=					MODEL_FOR_VISION_2_SEQ_MAPPING
 UpperCAmelCase__    :    List[str]										=					TF_MODEL_FOR_VISION_2_SEQ_MAPPING






 def 	lowercase_						(			self  :Tuple	,				_A  :Optional[int]	,				_A  :List[Any]	,				_A  :Optional[Any]			)				->			Optional[int]:







       '''simple docstring'''



       __A       	=			pipeline('image-to-text'	,				model=_A	,				tokenizer=_A	,				image_processor=_A			)
       __A       	=			[
           Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'			),
           './tests/fixtures/tests_samples/COCO/000000039769.png',
       ]
       return pipe, examples






 def 	lowercase_						(			self  :int	,				_A  :List[Any]	,				_A  :Any			)				->			Any:







       '''simple docstring'''



       __A       	=			pipe(_A			)
       self.assertEqual(
           _A	,				[
               [{'generated_text': ANY(_A			)}],
               [{'generated_text': ANY(_A			)}],
           ]	,				)






 @require_tf
 def 	lowercase_						(			self  :int			)				->			Dict:







       '''simple docstring'''



       __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(_A			)
       self.assertEqual(
           _A	,				[
               {
                   'generated_text': 'growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO'
               },
           ]	,				)

       __A       	=			pipe([image, image]			)
       self.assertEqual(
           _A	,				[
               [
                   {
                       'generated_text': 'growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO'
                   }
               ],
               [
                   {
                       'generated_text': 'growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO'
                   }
               ],
           ]	,				)

       __A       	=			pipe(_A	,				max_new_tokens=1			)
       self.assertEqual(
           _A	,				[{'generated_text': 'growth'}]	,				)






 @require_torch
 def 	lowercase_						(			self  :str			)				->			Optional[Any]:







       '''simple docstring'''



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

       __A       	=			pipe(_A			)
       self.assertEqual(
           _A	,				[
               {
                   'generated_text': 'growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO'
               },
           ]	,				)

       __A       	=			pipe([image, image]			)
       self.assertEqual(
           _A	,				[
               [
                   {
                       'generated_text': 'growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO'
                   }
               ],
               [
                   {
                       'generated_text': 'growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO'
                   }
               ],
           ]	,				)






 @require_torch
 def 	lowercase_						(			self  :List[str]			)				->			Any:







       '''simple docstring'''



       __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(_A	,				prompt=_A			)
       self.assertTrue(outputs[0]['generated_text'].startswith(_A			)			)






 @slow
 @require_torch
 def 	lowercase_						(			self  :Union[str, Any]			)				->			List[Any]:







       '''simple docstring'''



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

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

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







       '''simple docstring'''



       __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(_A	,				stream=_A			).raw			)

       __A       	=			pipe(_A			)
       self.assertEqual(_A	,				[{'generated_text': 'a pink pokemon pokemon with a blue shirt and a blue shirt'}]			)






 @slow
 @require_torch
 def 	lowercase_						(			self  :List[str]			)				->			Dict:







       '''simple docstring'''



       __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(_A	,				stream=_A			).raw			)

       __A       	=			pipe(_A			)
       self.assertEqual(_A	,				[{'generated_text': 'a cartoon of a purple character.'}]			)






 @slow
 @require_torch
 def 	lowercase_						(			self  :Optional[int]			)				->			Optional[Any]:







       '''simple docstring'''



       __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(_A	,				stream=_A			).raw			)

       __A       	=			'a photography of'

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

       with self.assertRaises(_A			):
             __A       	=			pipe([image, image]	,				prompt=[prompt, prompt]			)






 @slow
 @require_torch
 def 	lowercase_						(			self  :Union[str, Any]			)				->			Union[str, Any]:







       '''simple docstring'''



       __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(_A	,				stream=_A			).raw			)

       __A       	=			'a photo of a'

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

       with self.assertRaises(_A			):
             __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 	lowercase_						(			self  :Union[str, Any]			)				->			Dict:







       '''simple docstring'''



       __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(_A	,				stream=_A			).raw			)

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

       __A       	=			pipe(_A	,				prompt=_A			)
       self.assertEqual(_A	,				[{'generated_text': 'ash cloud'}]			)

       with self.assertRaises(_A			):
             __A       	=			pipe([image, image]	,				prompt=[prompt, prompt]			)






 @slow
 @require_tf
 def 	lowercase_						(			self  :int			)				->			Tuple:







       '''simple docstring'''



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

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

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





import hashlib
import importlib.util
import json
import os
import pathlib
from types import ModuleType

import pytest
import requests

a__		:   List[Any]            =       pathlib.Path.cwd().joinpath("project_euler")
a__		:   Union[str, Any]            =       pathlib.Path.cwd().joinpath(
    "scripts", "project_euler_answers.json"
)

with open(PROJECT_EULER_ANSWERS_PATH) as file_handle:
 a__		:   dict[str, str]            =       json.load(file_handle)





def        snake_case							(		UpperCAmelCase	)->			ModuleType:







      """simple docstring"""
      __A       	=			importlib.util.spec_from_file_location(file_path.name      ,  str(UpperCAmelCase	)	)
      __A       	=			importlib.util.module_from_spec(UpperCAmelCase	)  # type: ignore
      spec.loader.exec_module(UpperCAmelCase	)  # type: ignore
      return module





def        snake_case							(		)->			list[pathlib.Path]:







      """simple docstring"""
      __A       	=			[]
      for problem_dir_path in PROJECT_EULER_DIR_PATH.iterdir():
            if problem_dir_path.is_file() or problem_dir_path.name.startswith('_'	):
                  continue
            for file_path in problem_dir_path.iterdir():
                  if file_path.suffix != ".py" or file_path.name.startswith(('_', 'test')	):
                        continue
                  solution_file_paths.append(UpperCAmelCase	)
      return solution_file_paths





def        snake_case							(		)->			str:







      """simple docstring"""
      with open(os.environ['GITHUB_EVENT_PATH']	) as file:
            __A       	=			json.load(UpperCAmelCase	)
      return event["pull_request"]["url"] + "/files"





def        snake_case							(		)->			list[pathlib.Path]:







      """simple docstring"""
      __A       	=			[]
      __A       	=			{
          'Accept': 'application/vnd.github.v3+json',
          'Authorization': 'token ' + os.environ['GITHUB_TOKEN'],
      }
      __A       	=			requests.get(get_files_url()      ,  headers=UpperCAmelCase	).json()
      for file in files:
            __A       	=			pathlib.Path.cwd().joinpath(file['filename']	)
            if (
                filepath.suffix != ".py"
                or filepath.name.startswith(('_', 'test')	)
                or not filepath.name.startswith('sol'	)
            ):
                  continue
            solution_file_paths.append(UpperCAmelCase	)
      return solution_file_paths





def        snake_case							(		)->			list[pathlib.Path]:







      """simple docstring"""
      if os.environ.get('CI'	) and os.environ.get('GITHUB_EVENT_NAME'	) == "pull_request":
            # Return only if there are any, otherwise default to all solutions
            if filepaths := added_solution_file_path():
                  return filepaths
      return all_solution_file_paths()





@pytest.mark.parametrize(
    'solution_path'      ,  collect_solution_file_paths()      ,  ids=lambda UpperCAmelCase	: f'{path.parent.name}/{path.name}'      ,  )
def        snake_case							(		UpperCAmelCase	)->			None:







      """simple docstring"""
      __A       	=			solution_path.parent.name[8:].zfill(3	)
      __A       	=			PROBLEM_ANSWERS[problem_number]
      __A       	=			convert_path_to_module(UpperCAmelCase	)
      __A       	=			str(solution_module.solution()	)  # type: ignore
      __A       	=			hashlib.shaaaa(answer.encode()	).hexdigest()
      assert (
          answer == expected
      ), f'Expected solution to {problem_number} to have hash {expected}, got {answer}'






