




'''simple docstring'''






import copy
import fnmatch
import json
import os
import pickle as pkl
import shutil
import sys
import tarfile
import tempfile
from collections import OrderedDict
from contextlib import contextmanager
from functools import partial
from hashlib import shaaaa
from io import BytesIO
from pathlib import Path
from urllib.parse import urlparse
from zipfile import ZipFile, is_zipfile

import cva
import numpy as np
import requests
import wget
from filelock import FileLock
from PIL import Image
from tqdm.auto import tqdm
from yaml import Loader, dump, load


try:
      import torch

      lowercase						:   Tuple      						=							True
except ImportError:
      lowercase						:   List[Any]      						=							False


try:
      from torch.hub import _get_torch_home

      lowercase						:   Tuple      						=							_get_torch_home()
except ImportError:
      lowercase						:   Union[str, Any]      						=							os.path.expanduser(
          os.getenv('''TORCH_HOME''', os.path.join(os.getenv('''XDG_CACHE_HOME''', '''~/.cache'''), '''torch'''))
      )

lowercase						:   str      						=							os.path.join(torch_cache_home, '''transformers''')

lowercase						:   Union[str, Any]      						=							'''https://cdn.huggingface.co'''
lowercase						:   str      						=							'''https://s3.amazonaws.com/models.huggingface.co/bert'''
lowercase						:   Tuple      						=							'''/'''.join(str(Path(__file__).resolve()).split('''/''')[:-1])
lowercase						:   List[Any]      						=							os.path.join(PATH, '''config.yaml''')
lowercase						:   Dict      						=							os.path.join(PATH, '''attributes.txt''')
lowercase						:   List[str]      						=							os.path.join(PATH, '''objects.txt''')
lowercase						:   Dict      						=							os.getenv('''PYTORCH_PRETRAINED_BERT_CACHE''', default_cache_path)
lowercase						:   Tuple      						=							os.getenv('''PYTORCH_TRANSFORMERS_CACHE''', PYTORCH_PRETRAINED_BERT_CACHE)
lowercase						:   Union[str, Any]      						=							os.getenv('''TRANSFORMERS_CACHE''', PYTORCH_TRANSFORMERS_CACHE)
lowercase						:   int      						=							'''pytorch_model.bin'''
lowercase						:   List[str]      						=							'''config.yaml'''




def 		a_(			lowerCamelCase=OBJECTS ,					lowerCamelCase=ATTRIBUTES   )					->Union[str, Any]:






       '''simple docstring'''




       lowercase	:		Optional[Any]    =   []
       with open(lowerCamelCase   ) as f:
              for object in f.readlines():
                     vg_classes.append(object.split(''','''   )[0].lower().strip()   )

       lowercase	:		Any    =   []
       with open(lowerCamelCase   ) as f:
              for object in f.readlines():
                     vg_attrs.append(object.split(''','''   )[0].lower().strip()   )
       return vg_classes, vg_attrs




def 		a_(			lowerCamelCase   )					->Optional[Any]:






       '''simple docstring'''




       lowercase	:		int    =   OrderedDict()
       with open(lowerCamelCase ,					'''rb'''   ) as f:
              lowercase	:		Dict    =   pkl.load(lowerCamelCase   )['''model''']
       for k in copy.deepcopy(list(ckp.keys()   )   ):
              lowercase	:		List[str]    =   ckp.pop(lowerCamelCase   )
              if isinstance(lowerCamelCase ,					np.ndarray   ):
                     lowercase	:		Optional[int]    =   torch.tensor(lowerCamelCase   )
              else:
                     assert isinstance(lowerCamelCase ,					torch.tensor   ), type(lowerCamelCase   )
              lowercase	:		Dict    =   v
       return r

class 	SCREAMING_SNAKE_CASE_		:
 __snake_case						:  List[Any]       =   {}



 def __init__(	self ,		A ,		A = "root" ,		A=0			):






        '''simple docstring'''




        lowercase	:		Optional[Any]    =   name
        lowercase	:		int    =   level
        lowercase	:		Union[str, Any]    =   {}
        for k, v in dictionary.items():
               if v is None:
                      raise ValueError()
               lowercase	:		Any    =   copy.deepcopy(lowercase_			)
               lowercase	:		List[Any]    =   copy.deepcopy(lowercase_			)
               if isinstance(lowercase_ ,		lowercase_			):
                      lowercase	:		Union[str, Any]    =   Config(lowercase_ ,		name=lowercase_ ,		level=level + 1			)
               lowercase	:		Any    =   v
               setattr(self ,		lowercase_ ,		lowercase_			)

        lowercase	:		Any    =   d



 def __repr__(	self			):






        '''simple docstring'''




        return str(list((self._pointer.keys())			)			)



 def __setattr__(	self ,		A ,		A			):






        '''simple docstring'''




        lowercase	:		List[Any]    =   val
        lowercase	:		Optional[int]    =   val
        lowercase	:		Any    =   key.split('''.'''			)
        lowercase	:		Optional[int]    =   len(lowercase_			) - 1
        lowercase	:		List[Any]    =   self._pointer
        if len(lowercase_			) > 1:
               for i, l in enumerate(lowercase_			):
                      if hasattr(self ,		lowercase_			) and isinstance(getattr(self ,		lowercase_			) ,		lowercase_			):
                             setattr(getattr(self ,		lowercase_			) ,		'''.'''.join(levels[i:]			) ,		lowercase_			)
                      if l == last_level:
                             lowercase	:		List[str]    =   val
                      else:
                             lowercase	:		Optional[Any]    =   pointer[l]



 def  SCREAMING_SNAKE_CASE(	self			):






        '''simple docstring'''




        return self._pointer



 def  SCREAMING_SNAKE_CASE(	self ,		A ,		A			):






        '''simple docstring'''




        with open(f"""{file_name}""" ,		'''w'''			) as stream:
               dump(lowercase_ ,		lowercase_			)



 def  SCREAMING_SNAKE_CASE(	self ,		A ,		A			):






        '''simple docstring'''




        with open(f"""{file_name}""" ,		'''w'''			) as stream:
               json.dump(lowercase_ ,		lowercase_			)



 @staticmethod
 def  SCREAMING_SNAKE_CASE(	A			):






        '''simple docstring'''




        with open(lowercase_			) as stream:
               lowercase	:		List[Any]    =   load(lowercase_ ,		Loader=lowercase_			)
        return data



 def __str__(	self			):






        '''simple docstring'''




        lowercase	:		Optional[int]    =   '''    '''
        if self._name != "root":
               lowercase	:		Dict    =   f"""{t * (self._level-1)}{self._name}:\n"""
        else:
               lowercase	:		Optional[Any]    =   ''''''
        lowercase	:		Dict    =   self._level
        for i, (k, v) in enumerate(self._pointer.items()			):
               if isinstance(lowercase_ ,		lowercase_			):
                      r += f"""{t * (self._level)}{v}\n"""
                      self._level += 1
               else:
                      r += f"""{t * (self._level)}{k}: {v} ({type(lowercase_			).__name__})\n"""
               lowercase	:		Any    =   level
        return r[:-1]



 @classmethod
 def  SCREAMING_SNAKE_CASE(	cls ,		A ,		**A			):






        '''simple docstring'''




        lowercase,  lowercase	:		List[Any]    =   cls.get_config_dict(lowercase_ ,		**lowercase_			)
        return cls(lowercase_			)





 @classmethod
 def  SCREAMING_SNAKE_CASE(	cls ,		A ,		**A			):






        '''simple docstring'''




        lowercase	:		int    =   kwargs.pop('''cache_dir''' ,		lowercase_			)
        lowercase	:		int    =   kwargs.pop('''force_download''' ,		lowercase_			)
        lowercase	:		Optional[Any]    =   kwargs.pop('''resume_download''' ,		lowercase_			)
        lowercase	:		Optional[int]    =   kwargs.pop('''proxies''' ,		lowercase_			)
        lowercase	:		Union[str, Any]    =   kwargs.pop('''local_files_only''' ,		lowercase_			)

        if os.path.isdir(lowercase_			):
               lowercase	:		Optional[Any]    =   os.path.join(lowercase_ ,		lowercase_			)
        elif os.path.isfile(lowercase_			) or is_remote_url(lowercase_			):
               lowercase	:		Tuple    =   pretrained_model_name_or_path
        else:
               lowercase	:		Dict    =   hf_bucket_url(lowercase_ ,		filename=lowercase_ ,		use_cdn=lowercase_			)

        try:
               # Load from URL or cache if already cached
               lowercase	:		Optional[int]    =   cached_path(
                   lowercase_ ,		cache_dir=lowercase_ ,		force_download=lowercase_ ,		proxies=lowercase_ ,		resume_download=lowercase_ ,		local_files_only=lowercase_ ,		)
               # Load config dict
               if resolved_config_file is None:
                      raise EnvironmentError

               lowercase	:		str    =   Config.load_yaml(lowercase_			)

        except EnvironmentError:
               lowercase	:		Optional[int]    =   '''Can\'t load config for'''
               raise EnvironmentError(lowercase_			)

        if resolved_config_file == config_file:
               print('''loading configuration file from path'''			)
        else:
               print('''loading configuration file cache'''			)

        return Config.load_yaml(lowercase_			), kwargs






def 		a_(			lowerCamelCase   )					->str:






       '''simple docstring'''




       lowercase	:		List[str]    =   torch.load('''dump.pt''' ,					map_location=in_tensor.device   )
       lowercase	:		int    =   in_tensor.numpy()
       lowercase	:		int    =   out_tensor.numpy()[0]
       print(na.shape ,					na[0, 0, :5]   )
       print(na.shape ,					na[0, 0, :5]   )
       assert np.allclose(lowerCamelCase ,					lowerCamelCase ,					rtol=0.01 ,					atol=0.1   ), (
           f"""{sum([1 for x in np.isclose(lowerCamelCase ,					lowerCamelCase ,					rtol=0.01 ,					atol=0.1   ).flatten() if x is False]   )/len(na.flatten()   )*100:.4f} %"""
           " element-wise mismatch"
       )
       raise Exception('''tensors are all good'''   )

       # Hugging face functions below




def 		a_(			lowerCamelCase   )					->List[Any]:






       '''simple docstring'''




       lowercase	:		int    =   urlparse(lowerCamelCase   )
       return parsed.scheme in ("http", "https")




def 		a_(			lowerCamelCase ,					lowerCamelCase ,					lowerCamelCase=True   )					->str:






       '''simple docstring'''




       lowercase	:		Tuple    =   CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
       lowercase	:		int    =   '''/''' not in model_id
       if legacy_format:
              return f"""{endpoint}/{model_id}-{filename}"""
       else:
              return f"""{endpoint}/{model_id}/{filename}"""




def 		a_(			lowerCamelCase ,					lowerCamelCase ,					lowerCamelCase=None ,					lowerCamelCase=0 ,					lowerCamelCase=None ,					)					->List[Any]:






       '''simple docstring'''




       lowercase	:		Tuple    =   '''python/{}'''.format(sys.version.split()[0]   )
       if _torch_available:
              ua += "; torch/{}".format(torch.__version__   )
       if isinstance(lowerCamelCase ,					lowerCamelCase   ):
              ua += "; " + "; ".join('''{}/{}'''.format(lowerCamelCase ,					lowerCamelCase   ) for k, v in user_agent.items()   )
       elif isinstance(lowerCamelCase ,					lowerCamelCase   ):
              ua += "; " + user_agent
       lowercase	:		List[Any]    =   {'''user-agent''': ua}
       if resume_size > 0:
              lowercase	:		Optional[Any]    =   '''bytes=%d-''' % (resume_size,)
       lowercase	:		Union[str, Any]    =   requests.get(lowerCamelCase ,					stream=lowerCamelCase ,					proxies=lowerCamelCase ,					headers=lowerCamelCase   )
       if response.status_code == 416:  # Range not satisfiable
              return
       lowercase	:		Tuple    =   response.headers.get('''Content-Length'''   )
       lowercase	:		Union[str, Any]    =   resume_size + int(lowerCamelCase   ) if content_length is not None else None
       lowercase	:		List[Any]    =   tqdm(
           unit='''B''' ,					unit_scale=lowerCamelCase ,					total=lowerCamelCase ,					initial=lowerCamelCase ,					desc='''Downloading''' ,					)
       for chunk in response.iter_content(chunk_size=1024   ):
              if chunk:  # filter out keep-alive new chunks
                     progress.update(len(lowerCamelCase   )   )
                     temp_file.write(lowerCamelCase   )
       progress.close()




def 		a_(			lowerCamelCase ,					lowerCamelCase=None ,					lowerCamelCase=False ,					lowerCamelCase=None ,					lowerCamelCase=10 ,					lowerCamelCase=False ,					lowerCamelCase=None ,					lowerCamelCase=False ,					)					->Dict:






       '''simple docstring'''




       if cache_dir is None:
              lowercase	:		Dict    =   TRANSFORMERS_CACHE
       if isinstance(lowerCamelCase ,					lowerCamelCase   ):
              lowercase	:		Union[str, Any]    =   str(lowerCamelCase   )

       os.makedirs(lowerCamelCase ,					exist_ok=lowerCamelCase   )

       lowercase	:		Optional[int]    =   None
       if not local_files_only:
              try:
                     lowercase	:		Optional[Any]    =   requests.head(lowerCamelCase ,					allow_redirects=lowerCamelCase ,					proxies=lowerCamelCase ,					timeout=lowerCamelCase   )
                     if response.status_code == 200:
                            lowercase	:		List[Any]    =   response.headers.get('''ETag'''   )
              except (EnvironmentError, requests.exceptions.Timeout):
                     # etag is already None
                     pass

       lowercase	:		Any    =   url_to_filename(lowerCamelCase ,					lowerCamelCase   )

       # get cache path to put the file
       lowercase	:		int    =   os.path.join(lowerCamelCase ,					lowerCamelCase   )

       # etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible.
       # try to get the last downloaded one
       if etag is None:
              if os.path.exists(lowerCamelCase   ):
                     return cache_path
              else:
                     lowercase	:		Tuple    =   [
                         file
                         for file in fnmatch.filter(os.listdir(lowerCamelCase   ) ,					filename + '''.*'''   )
                         if not file.endswith('''.json'''   ) and not file.endswith('''.lock'''   )
                     ]
                     if len(lowerCamelCase   ) > 0:
                            return os.path.join(lowerCamelCase ,					matching_files[-1]   )
                     else:
                            # If files cannot be found and local_files_only=True,
                            # the models might've been found if local_files_only=False
                            # Notify the user about that
                            if local_files_only:
                                   raise ValueError(
                                       '''Cannot find the requested files in the cached path and outgoing traffic has been'''
                                       ''' disabled. To enable model look-ups and downloads online, set \'local_files_only\''''
                                       ''' to False.'''   )
                            return None

    # From now on, etag is not None.
       if os.path.exists(lowerCamelCase   ) and not force_download:
              return cache_path

       # Prevent parallel downloads of the same file with a lock.
       lowercase	:		str    =   cache_path + '''.lock'''
       with FileLock(lowerCamelCase   ):
              # If the download just completed while the lock was activated.
              if os.path.exists(lowerCamelCase   ) and not force_download:
                     # Even if returning early like here, the lock will be released.
                     return cache_path

              if resume_download:
                     lowercase	:		Tuple    =   cache_path + '''.incomplete'''

                     @contextmanager
                     def _resumable_file_manager():
                            with open(lowerCamelCase ,					'''a+b'''   ) as f:
                                   yield f

                     lowercase	:		Union[str, Any]    =   _resumable_file_manager
                     if os.path.exists(lowerCamelCase   ):
                            lowercase	:		Tuple    =   os.stat(lowerCamelCase   ).st_size
                     else:
                            lowercase	:		Optional[int]    =   0
              else:
                     lowercase	:		List[Any]    =   partial(tempfile.NamedTemporaryFile ,					dir=lowerCamelCase ,					delete=lowerCamelCase   )
                     lowercase	:		Dict    =   0

              # Download to temporary file, then copy to cache dir once finished.
              # Otherwise you get corrupt cache entries if the download gets interrupted.
              with temp_file_manager() as temp_file:
                     print(
                         '''%s not found in cache or force_download set to True, downloading to %s''' ,					lowerCamelCase ,					temp_file.name ,					)

                     http_get(
                         lowerCamelCase ,					lowerCamelCase ,					proxies=lowerCamelCase ,					resume_size=lowerCamelCase ,					user_agent=lowerCamelCase ,					)

              os.replace(temp_file.name ,					lowerCamelCase   )

              lowercase	:		Optional[Any]    =   {'''url''': url, '''etag''': etag}
              lowercase	:		Optional[int]    =   cache_path + '''.json'''
              with open(lowerCamelCase ,					'''w'''   ) as meta_file:
                     json.dump(lowerCamelCase ,					lowerCamelCase   )

       return cache_path




def 		a_(			lowerCamelCase ,					lowerCamelCase=None   )					->Any:






       '''simple docstring'''




       lowercase	:		List[Any]    =   url.encode('''utf-8'''   )
       lowercase	:		Optional[int]    =   shaaaa(lowerCamelCase   )
       lowercase	:		List[str]    =   url_hash.hexdigest()

       if etag:
              lowercase	:		List[Any]    =   etag.encode('''utf-8'''   )
              lowercase	:		Optional[Any]    =   shaaaa(lowerCamelCase   )
              filename += "." + etag_hash.hexdigest()

       if url.endswith('''.h5'''   ):
              filename += ".h5"

       return filename




def 		a_(			lowerCamelCase ,					lowerCamelCase=None ,					lowerCamelCase=False ,					lowerCamelCase=None ,					lowerCamelCase=False ,					lowerCamelCase=None ,					lowerCamelCase=False ,					lowerCamelCase=False ,					lowerCamelCase=False ,					)					->Any:






       '''simple docstring'''




       if cache_dir is None:
              lowercase	:		Dict    =   TRANSFORMERS_CACHE
       if isinstance(lowerCamelCase ,					lowerCamelCase   ):
              lowercase	:		Union[str, Any]    =   str(lowerCamelCase   )
       if isinstance(lowerCamelCase ,					lowerCamelCase   ):
              lowercase	:		int    =   str(lowerCamelCase   )

       if is_remote_url(lowerCamelCase   ):
              # URL, so get it from the cache (downloading if necessary)
              lowercase	:		Union[str, Any]    =   get_from_cache(
                  lowerCamelCase ,					cache_dir=lowerCamelCase ,					force_download=lowerCamelCase ,					proxies=lowerCamelCase ,					resume_download=lowerCamelCase ,					user_agent=lowerCamelCase ,					local_files_only=lowerCamelCase ,					)
       elif os.path.exists(lowerCamelCase   ):
              # File, and it exists.
              lowercase	:		Tuple    =   url_or_filename
       elif urlparse(lowerCamelCase   ).scheme == "":
              # File, but it doesn't exist.
              raise EnvironmentError('''file {} not found'''.format(lowerCamelCase   )   )
       else:
              # Something unknown
              raise ValueError('''unable to parse {} as a URL or as a local path'''.format(lowerCamelCase   )   )

       if extract_compressed_file:
              if not is_zipfile(lowerCamelCase   ) and not tarfile.is_tarfile(lowerCamelCase   ):
                     return output_path

              # Path where we extract compressed archives
              # We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/"
              lowercase,  lowercase	:		List[str]    =   os.path.split(lowerCamelCase   )
              lowercase	:		str    =   output_file.replace('''.''' ,					'''-'''   ) + '''-extracted'''
              lowercase	:		Any    =   os.path.join(lowerCamelCase ,					lowerCamelCase   )

              if os.path.isdir(lowerCamelCase   ) and os.listdir(lowerCamelCase   ) and not force_extract:
                     return output_path_extracted

              # Prevent parallel extractions
              lowercase	:		Tuple    =   output_path + '''.lock'''
              with FileLock(lowerCamelCase   ):
                     shutil.rmtree(lowerCamelCase ,					ignore_errors=lowerCamelCase   )
                     os.makedirs(lowerCamelCase   )
                     if is_zipfile(lowerCamelCase   ):
                            with ZipFile(lowerCamelCase ,					'''r'''   ) as zip_file:
                                   zip_file.extractall(lowerCamelCase   )
                                   zip_file.close()
                     elif tarfile.is_tarfile(lowerCamelCase   ):
                            lowercase	:		Union[str, Any]    =   tarfile.open(lowerCamelCase   )
                            tar_file.extractall(lowerCamelCase   )
                            tar_file.close()
                     else:
                            raise EnvironmentError('''Archive format of {} could not be identified'''.format(lowerCamelCase   )   )

              return output_path_extracted

       return output_path




def 		a_(			lowerCamelCase ,					lowerCamelCase=","   )					->Tuple:






       '''simple docstring'''




       assert isinstance(lowerCamelCase ,					lowerCamelCase   )
       if os.path.isfile(lowerCamelCase   ):
              with open(lowerCamelCase   ) as f:
                     lowercase	:		int    =   eval(f.read()   )
       else:
              lowercase	:		Optional[int]    =   requests.get(lowerCamelCase   )
              try:
                     lowercase	:		Optional[int]    =   requests.json()
              except Exception:
                     lowercase	:		int    =   req.content.decode()
                     assert data is not None, "could not connect"
                     try:
                            lowercase	:		List[str]    =   eval(lowerCamelCase   )
                     except Exception:
                            lowercase	:		int    =   data.split('''\n'''   )
              req.close()
       return data




def 		a_(			lowerCamelCase   )					->Any:






       '''simple docstring'''




       lowercase	:		Union[str, Any]    =   requests.get(lowerCamelCase   )
       lowercase	:		str    =   np.array(Image.open(BytesIO(response.content   )   )   )
       return img




def 		a_(			lowerCamelCase   )					->List[Any]:






       '''simple docstring'''




       lowercase	:		List[Any]    =   url.split('''/'''   )[-1]
       if fn not in os.listdir(os.getcwd()   ):
              wget.download(lowerCamelCase   )
       with open(lowerCamelCase ,					'''rb'''   ) as stream:
              lowercase	:		Union[str, Any]    =   pkl.load(lowerCamelCase   )
       lowercase	:		Optional[int]    =   weights.pop('''model'''   )
       lowercase	:		Optional[Any]    =   {}
       for k, v in model.items():
              lowercase	:		List[Any]    =   torch.from_numpy(lowerCamelCase   )
              if "running_var" in k:
                     lowercase	:		Optional[Any]    =   torch.tensor([0]   )
                     lowercase	:		List[str]    =   k.replace('''running_var''' ,					'''num_batches_tracked'''   )
                     lowercase	:		Dict    =   zero
       return new




def 		a_(			)					->Any:






       '''simple docstring'''




       print(f"""{os.path.abspath(os.path.join(lowerCamelCase ,					os.pardir   )   )}/demo.ipynb"""   )




def 		a_(			lowerCamelCase ,					lowerCamelCase="RGB"   )					->str:






       '''simple docstring'''




       assert isinstance(lowerCamelCase ,					lowerCamelCase   )
       if os.path.isfile(lowerCamelCase   ):
              lowercase	:		List[str]    =   cva.imread(lowerCamelCase   )
       else:
              lowercase	:		List[str]    =   get_image_from_url(lowerCamelCase   )
              assert img is not None, f"""could not connect to: {im}"""
       lowercase	:		int    =   cva.cvtColor(lowerCamelCase ,					cva.COLOR_BGR2RGB   )
       if input_format == "RGB":
              lowercase	:		Any    =   img[:, :, ::-1]
       return img





def 		a_(			lowerCamelCase ,					lowerCamelCase=1   )					->Any:






       '''simple docstring'''




       return (images[i : i + batch] for i in range(0 ,					len(lowerCamelCase   ) ,					lowerCamelCase   ))







'''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_     =      False


if is_vision_available():
						from PIL import Image
else:







						class lowerCamelCase   :

										@staticmethod
										def 					_lowerCamelCase    (       *lowercase_,						**lowercase_ )    ->							List[Any]:
											pass







@is_pipeline_test
@require_vision
class lowerCamelCase   (    unittest.TestCase				):
				snake_case_							     = MODEL_FOR_VISION_2_SEQ_MAPPING
				snake_case_							     = TF_MODEL_FOR_VISION_2_SEQ_MAPPING

				def 					_lowerCamelCase    (       self,						lowercase_,						lowercase_,						lowercase_ )    ->							Optional[Any]:
					snake_case							=					pipeline('image-to-text',						model=lowercase_,						tokenizer=lowercase_,						image_processor=lowercase_ )
					snake_case							=					[
					    Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ),
					    './tests/fixtures/tests_samples/COCO/000000039769.png',
					]
					return pipe, examples

				def 					_lowerCamelCase    (       self,						lowercase_,						lowercase_ )    ->							Tuple:
					snake_case							=					pipe(lowercase_ )
					self.assertEqual(
					    lowercase_,						[
					        [{'generated_text': ANY(lowercase_ )}],
					        [{'generated_text': ANY(lowercase_ )}],
					    ],						)

				@require_tf
				def 					_lowerCamelCase    (       self )    ->							int:
					snake_case							=					pipeline('image-to-text',						model='hf-internal-testing/tiny-random-vit-gpt2',						framework='tf' )
					snake_case							=					'./tests/fixtures/tests_samples/COCO/000000039769.png'

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

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

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

				@require_torch
				def 					_lowerCamelCase    (       self )    ->							Tuple:
					snake_case							=					pipeline('image-to-text',						model='hf-internal-testing/tiny-random-vit-gpt2' )
					snake_case							=					'./tests/fixtures/tests_samples/COCO/000000039769.png'

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

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

				@require_torch
				def 					_lowerCamelCase    (       self )    ->							Union[str, Any]:
					snake_case							=					pipeline('image-to-text',						model='hf-internal-testing/tiny-random-BlipForConditionalGeneration' )
					snake_case							=					'./tests/fixtures/tests_samples/COCO/000000039769.png'
					snake_case							=					'a photo of'

					snake_case							=					pipe(lowercase_,						prompt=lowercase_ )
					self.assertTrue(outputs[0]['generated_text'].startswith(lowercase_ ) )

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

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

					snake_case							=					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 					_lowerCamelCase    (       self )    ->							List[Any]:
					snake_case							=					pipeline('image-to-text',						model='Salesforce/blip-image-captioning-base' )
					snake_case							=					'https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/pokemon.png'
					snake_case							=					Image.open(requests.get(lowercase_,						stream=lowercase_ ).raw )

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

				@slow
				@require_torch
				def 					_lowerCamelCase    (       self )    ->							Dict:
					snake_case							=					pipeline('image-to-text',						model='microsoft/git-base-coco' )
					snake_case							=					'https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/pokemon.png'
					snake_case							=					Image.open(requests.get(lowercase_,						stream=lowercase_ ).raw )

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

				@slow
				@require_torch
				def 					_lowerCamelCase    (       self )    ->							Optional[Any]:
					snake_case							=					pipeline('image-to-text',						model='Salesforce/blip-image-captioning-base' )
					snake_case							=					'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg'
					snake_case							=					Image.open(requests.get(lowercase_,						stream=lowercase_ ).raw )

					snake_case							=					'a photography of'

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

					with self.assertRaises(lowercase_ ):
						snake_case							=					pipe([image, image],						prompt=[prompt, prompt] )

				@slow
				@require_torch
				def 					_lowerCamelCase    (       self )    ->							Dict:
					snake_case							=					pipeline('image-to-text',						model='microsoft/git-base-coco' )
					snake_case							=					'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg'
					snake_case							=					Image.open(requests.get(lowercase_,						stream=lowercase_ ).raw )

					snake_case							=					'a photo of a'

					snake_case							=					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_ ):
						snake_case							=					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 )    ->							Any:
					snake_case							=					pipeline('image-to-text',						model='google/pix2struct-ai2d-base' )
					snake_case							=					'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg'
					snake_case							=					Image.open(requests.get(lowercase_,						stream=lowercase_ ).raw )

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

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

					with self.assertRaises(lowercase_ ):
						snake_case							=					pipe([image, image],						prompt=[prompt, prompt] )






				@slow
				@require_tf
				def 					_lowerCamelCase    (       self )    ->							Optional[int]:
					snake_case							=					pipeline('image-to-text',						model='ydshieh/vit-gpt2-coco-en',						framework='tf' )
					snake_case							=					'./tests/fixtures/tests_samples/COCO/000000039769.png'

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

					snake_case							=					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 '}],
					    ],						)





