code: 
  
  
  
  
  import argparse
  import logging
  import os
  from pathlib import Path
  from typing import Any, Dict
  
  import pytorch_lightning as pl
  from pytorch_lightning.utilities import rank_zero_info
  
  from transformers import (
      AdamW,
      AutoConfig,
      AutoModel,
      AutoModelForPreTraining,
      AutoModelForQuestionAnswering,
      AutoModelForSeqaSeqLM,
      AutoModelForSequenceClassification,
      AutoModelForTokenClassification,
      AutoModelWithLMHead,
      AutoTokenizer,
      PretrainedConfig,
      PreTrainedTokenizer,
  )
  from transformers.optimization import (
      Adafactor,
      get_cosine_schedule_with_warmup,
      get_cosine_with_hard_restarts_schedule_with_warmup,
      get_linear_schedule_with_warmup,
      get_polynomial_decay_schedule_with_warmup,
  )
  from transformers.utils.versions import require_version
  
  
  lowercase__			=	logging.getLogger(__name__)
  
  require_version('''pytorch_lightning>=1.0.4''')
  
  lowercase__			=	{
      '''base''': AutoModel,
      '''sequence-classification''': AutoModelForSequenceClassification,
      '''question-answering''': AutoModelForQuestionAnswering,
      '''pretraining''': AutoModelForPreTraining,
      '''token-classification''': AutoModelForTokenClassification,
      '''language-modeling''': AutoModelWithLMHead,
      '''summarization''': AutoModelForSeqaSeqLM,
      '''translation''': AutoModelForSeqaSeqLM,
  }
  
  
  # update this and the import above to support new schedulers from transformers.optimization
  lowercase__			=	{
      '''linear''': get_linear_schedule_with_warmup,
      '''cosine''': get_cosine_schedule_with_warmup,
      '''cosine_w_restarts''': get_cosine_with_hard_restarts_schedule_with_warmup,
      '''polynomial''': get_polynomial_decay_schedule_with_warmup,
      # '': get_constant_schedule,             # not supported for now
      # '': get_constant_schedule_with_warmup, # not supported for now
  }
  lowercase__			=	sorted(arg_to_scheduler.keys())
  lowercase__			=	'''{''' + ''', '''.join(arg_to_scheduler_choices) + '''}'''
  
  
  
  
  
  
  class 						lowercase     (   pl.LightningModule):
  
  
  
  
  
  
        def __init__(self ,  a__ ,  a__=None ,  a__="base" ,  a__=None ,  a__=None ,  a__=None ,  **a__ ,  )       ->   Optional[int]:
           super().__init__()
           # TODO: move to self.save_hyperparameters()
           # self.save_hyperparameters()
           # can also expand arguments into trainer signature for easier reading
  
           self.save_hyperparameters(a__					)
           SCREAMING_SNAKE_CASE__			:				str       						= 0
           SCREAMING_SNAKE_CASE__			:				Dict       						= Path(self.hparams.output_dir					)
           SCREAMING_SNAKE_CASE__			:				Any       						= self.hparams.cache_dir if self.hparams.cache_dir else None
           if config is None:
              SCREAMING_SNAKE_CASE__			:				str       						= AutoConfig.from_pretrained(
                  self.hparams.config_name if self.hparams.config_name else self.hparams.model_name_or_path ,  **({'''num_labels''': num_labels} if num_labels is not None else {}) ,  cache_dir=a__ ,  **a__ ,  )
           else:
              SCREAMING_SNAKE_CASE__			:				PretrainedConfig       						= config
  
           SCREAMING_SNAKE_CASE__			:				List[Any]       						= ("encoder_layerdrop", "decoder_layerdrop", "dropout", "attention_dropout")
           for p in extra_model_params:
              if getattr(self.hparams ,  a__ ,  a__					):
                 assert hasattr(self.config ,  a__					), f"""model config doesn\'t have a `{p}` attribute"""
                 setattr(self.config ,  a__ ,  getattr(self.hparams ,  a__					)					)
  
           if tokenizer is None:
              SCREAMING_SNAKE_CASE__			:				Optional[int]       						= AutoTokenizer.from_pretrained(
                  self.hparams.tokenizer_name if self.hparams.tokenizer_name else self.hparams.model_name_or_path ,  cache_dir=a__ ,  )
           else:
              SCREAMING_SNAKE_CASE__			:				PreTrainedTokenizer       						= tokenizer
           SCREAMING_SNAKE_CASE__			:				Tuple       						= MODEL_MODES[mode]
           if model is None:
              SCREAMING_SNAKE_CASE__			:				Any       						= self.model_type.from_pretrained(
                  self.hparams.model_name_or_path ,  from_tf=bool('''.ckpt''' in self.hparams.model_name_or_path					) ,  config=self.config ,  cache_dir=a__ ,  )
           else:
              SCREAMING_SNAKE_CASE__			:				List[str]       						= model
  
  
  
  
  
  
        def    A__(self ,  *a__ ,  **a__					)       ->   List[Any]:
           SCREAMING_SNAKE_CASE__			:				Optional[int]       						= self.model_type.from_pretrained(*a__ ,  **a__					)
  
  
  
  
  
  
        def    A__(self					)       ->   List[str]:
           SCREAMING_SNAKE_CASE__			:				Optional[int]       						= arg_to_scheduler[self.hparams.lr_scheduler]
           SCREAMING_SNAKE_CASE__			:				Any       						= get_schedule_func(
               self.opt ,  num_warmup_steps=self.hparams.warmup_steps ,  num_training_steps=self.total_steps()					)
           SCREAMING_SNAKE_CASE__			:				Optional[int]       						= {"scheduler": scheduler, "interval": "step", "frequency": 1}
           return scheduler
  
  
  
  
  
  
        def    A__(self					)       ->   Any:
           SCREAMING_SNAKE_CASE__			:				Union[str, Any]       						= self.model
           SCREAMING_SNAKE_CASE__			:				List[Any]       						= ["bias", "LayerNorm.weight"]
           SCREAMING_SNAKE_CASE__			:				Optional[Any]       						= [
               {
                   "params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay					)],
                   "weight_decay": self.hparams.weight_decay,
               },
               {
                   "params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay					)],
                   "weight_decay": 0.0,
               },
           ]
           if self.hparams.adafactor:
              SCREAMING_SNAKE_CASE__			:				Dict       						= Adafactor(
                  a__ ,  lr=self.hparams.learning_rate ,  scale_parameter=a__ ,  relative_step=a__					)
  
           else:
              SCREAMING_SNAKE_CASE__			:				Dict       						= AdamW(
                  a__ ,  lr=self.hparams.learning_rate ,  eps=self.hparams.adam_epsilon					)
           SCREAMING_SNAKE_CASE__			:				Optional[Any]       						= optimizer
  
           SCREAMING_SNAKE_CASE__			:				Optional[Any]       						= self.get_lr_scheduler()
  
           return [optimizer], [scheduler]
  
  
  
  
  
  
        def    A__(self ,  a__ ,  a__					)       ->   Any:
           return self.validation_step(a__ ,  a__					)
  
  
  
  
  
  
        def    A__(self ,  a__					)       ->   Tuple:
           return self.validation_end(a__					)
  
  
  
  
  
  
        def    A__(self					)       ->   Dict:
           SCREAMING_SNAKE_CASE__			:				List[Any]       						= max(1 ,  self.hparams.gpus					)  # TODO: consider num_tpu_cores
           SCREAMING_SNAKE_CASE__			:				List[Any]       						= self.hparams.train_batch_size * self.hparams.accumulate_grad_batches * num_devices
           return (self.dataset_size / effective_batch_size) * self.hparams.max_epochs
  
  
  
  
  
  
        def    A__(self ,  a__					)       ->   Any:
  
  
  
  
  
  
           if mode == "test":
              SCREAMING_SNAKE_CASE__			:				Union[str, Any]       						= len(self.test_dataloader().dataset					)
           else:
              SCREAMING_SNAKE_CASE__			:				Optional[Any]       						= self.get_dataloader('''train''' ,  self.hparams.train_batch_size ,  shuffle=a__					)
              SCREAMING_SNAKE_CASE__			:				List[Any]       						= len(self.train_dataloader().dataset					)
  
  
  
  
  
  
        def    A__(self ,  a__ ,  a__ ,  a__ = False					)       ->   List[str]:
           raise NotImplementedError('''You must implement this for your task'''					)
  
  
  
  
  
  
        def    A__(self					)       ->   Union[str, Any]:
           return self.train_loader
  
  
  
  
  
  
        def    A__(self					)       ->   Dict:
           return self.get_dataloader('''dev''' ,  self.hparams.eval_batch_size ,  shuffle=a__					)
  
  
  
  
  
  
        def    A__(self					)       ->   str:
           return self.get_dataloader('''test''' ,  self.hparams.eval_batch_size ,  shuffle=a__					)
  
  
  
  
  
  
        def    A__(self ,  a__					)       ->   Optional[int]:
           return os.path.join(
               self.hparams.data_dir ,  '''cached_{}_{}_{}'''.format(
                   a__ ,  list(filter(a__ ,  self.hparams.model_name_or_path.split('''/'''					)					)					).pop() ,  str(self.hparams.max_seq_length					) ,  ) ,  )
  
  
  
  
  
  
        @pl.utilities.rank_zero_only
        def    A__(self ,  a__					)       ->   str:
           SCREAMING_SNAKE_CASE__			:				List[Any]       						= self.output_dir.joinpath('''best_tfmr'''					)
           SCREAMING_SNAKE_CASE__			:				str       						= self.step_count
           self.model.save_pretrained(a__					)
           self.tokenizer.save_pretrained(a__					)
  
  
  
  
  
  
        @staticmethod
        def    A__(a__ ,  a__					)       ->   Union[str, Any]:
           parser.add_argument(
               '''--model_name_or_path''' ,  default=a__ ,  type=a__ ,  required=a__ ,  help='''Path to pretrained model or model identifier from huggingface.co/models''' ,  )
           parser.add_argument(
               '''--config_name''' ,  default='''''' ,  type=a__ ,  help='''Pretrained config name or path if not the same as model_name'''					)
           parser.add_argument(
               '''--tokenizer_name''' ,  default=a__ ,  type=a__ ,  help='''Pretrained tokenizer name or path if not the same as model_name''' ,  )
           parser.add_argument(
               '''--cache_dir''' ,  default='''''' ,  type=a__ ,  help='''Where do you want to store the pre-trained models downloaded from huggingface.co''' ,  )
           parser.add_argument(
               '''--encoder_layerdrop''' ,  type=a__ ,  help='''Encoder layer dropout probability (Optional). Goes into model.config''' ,  )
           parser.add_argument(
               '''--decoder_layerdrop''' ,  type=a__ ,  help='''Decoder layer dropout probability (Optional). Goes into model.config''' ,  )
           parser.add_argument(
               '''--dropout''' ,  type=a__ ,  help='''Dropout probability (Optional). Goes into model.config''' ,  )
           parser.add_argument(
               '''--attention_dropout''' ,  type=a__ ,  help='''Attention dropout probability (Optional). Goes into model.config''' ,  )
           parser.add_argument('''--learning_rate''' ,  default=5E-5 ,  type=a__ ,  help='''The initial learning rate for Adam.'''					)
           parser.add_argument(
               '''--lr_scheduler''' ,  default='''linear''' ,  choices=a__ ,  metavar=a__ ,  type=a__ ,  help='''Learning rate scheduler''' ,  )
           parser.add_argument('''--weight_decay''' ,  default=0.0 ,  type=a__ ,  help='''Weight decay if we apply some.'''					)
           parser.add_argument('''--adam_epsilon''' ,  default=1E-8 ,  type=a__ ,  help='''Epsilon for Adam optimizer.'''					)
           parser.add_argument('''--warmup_steps''' ,  default=0 ,  type=a__ ,  help='''Linear warmup over warmup_steps.'''					)
           parser.add_argument('''--num_workers''' ,  default=4 ,  type=a__ ,  help='''kwarg passed to DataLoader'''					)
           parser.add_argument('''--num_train_epochs''' ,  dest='''max_epochs''' ,  default=3 ,  type=a__					)
           parser.add_argument('''--train_batch_size''' ,  default=3_2 ,  type=a__					)
           parser.add_argument('''--eval_batch_size''' ,  default=3_2 ,  type=a__					)
           parser.add_argument('''--adafactor''' ,  action='''store_true'''					)
  
  
  
  
  
  
  class 						lowercase     (   pl.Callback):
  
  
  
  
  
  
        def    A__(self ,  a__ ,  a__					)       ->   Optional[Any]:
           SCREAMING_SNAKE_CASE__			:				str       						= trainer.lr_schedulers[0]["scheduler"]
           SCREAMING_SNAKE_CASE__			:				str       						= {f"""lr_group_{i}""": lr for i, lr in enumerate(lr_scheduler.get_lr()					)}
           pl_module.logger.log_metrics(a__					)
  
  
  
  
  
  
        def    A__(self ,  a__ ,  a__					)       ->   List[str]:
           rank_zero_info('''***** Validation results *****'''					)
           SCREAMING_SNAKE_CASE__			:				Any       						= trainer.callback_metrics
           # Log results
           for key in sorted(a__					):
              if key not in ["log", "progress_bar"]:
                 rank_zero_info('''{} = {}\n'''.format(a__ ,  str(metrics[key]					)					)					)
  
  
  
  
  
  
        def    A__(self ,  a__ ,  a__					)       ->   List[Any]:
           rank_zero_info('''***** Test results *****'''					)
           SCREAMING_SNAKE_CASE__			:				Optional[int]       						= trainer.callback_metrics
           # Log and save results to file
           SCREAMING_SNAKE_CASE__			:				Optional[Any]       						= os.path.join(pl_module.hparams.output_dir ,  '''test_results.txt'''					)
           with open(a__ ,  '''w'''					) as writer:
              for key in sorted(a__					):
                 if key not in ["log", "progress_bar"]:
                    rank_zero_info('''{} = {}\n'''.format(a__ ,  str(metrics[key]					)					)					)
                    writer.write('''{} = {}\n'''.format(a__ ,  str(metrics[key]					)					)					)
  
  
  def 				UpperCamelCase	(  snake_case	,     snake_case   ):
  
  
  
  
     '''simple docstring'''
  
     parser.add_argument(
         '''--output_dir'''	,     default=__lowerCAmelCase	,     type=__lowerCAmelCase	,     required=__lowerCAmelCase	,     help='''The output directory where the model predictions and checkpoints will be written.'''	,     )
     parser.add_argument(
         '''--fp16'''	,     action='''store_true'''	,     help='''Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit'''	,     )
  
     parser.add_argument(
         '''--fp16_opt_level'''	,     type=__lowerCAmelCase	,     default='''O2'''	,     help=(
             '''For fp16: Apex AMP optimization level selected in [\'O0\', \'O1\', \'O2\', and \'O3\'].'''
             '''See details at https://nvidia.github.io/apex/amp.html'''
         )	,     )
     parser.add_argument('''--n_tpu_cores'''	,     dest='''tpu_cores'''	,     type=__lowerCAmelCase   )
     parser.add_argument('''--max_grad_norm'''	,     dest='''gradient_clip_val'''	,     default=1.0	,     type=__lowerCAmelCase	,     help='''Max gradient norm'''   )
     parser.add_argument('''--do_train'''	,     action='''store_true'''	,     help='''Whether to run training.'''   )
     parser.add_argument('''--do_predict'''	,     action='''store_true'''	,     help='''Whether to run predictions on the test set.'''   )
     parser.add_argument(
         '''--gradient_accumulation_steps'''	,     dest='''accumulate_grad_batches'''	,     type=__lowerCAmelCase	,     default=1	,     help='''Number of updates steps to accumulate before performing a backward/update pass.'''	,     )
     parser.add_argument('''--seed'''	,     type=__lowerCAmelCase	,     default=42	,     help='''random seed for initialization'''   )
     parser.add_argument(
         '''--data_dir'''	,     default=__lowerCAmelCase	,     type=__lowerCAmelCase	,     required=__lowerCAmelCase	,     help='''The input data dir. Should contain the training files for the CoNLL-2003 NER task.'''	,     )
  
  
  
  
  
  
  
  def 				UpperCamelCase	(  snake_case	,     snake_case	,     snake_case=None	,     snake_case=True	,     snake_case=[]	,     snake_case=None	,     snake_case=None	,     **snake_case	,     ):
  
  
  
  
     '''simple docstring'''
  
     pl.seed_everything(args.seed   )
  
     # init model
     SCREAMING_SNAKE_CASE__			:				str       						= Path(model.hparams.output_dir   )
     odir.mkdir(exist_ok=__lowerCAmelCase   )
  
     # add custom checkpoints
     if checkpoint_callback is None:
        SCREAMING_SNAKE_CASE__			:				List[str]       						= pl.callbacks.ModelCheckpoint(
            filepath=args.output_dir	,     prefix='''checkpoint'''	,     monitor='''val_loss'''	,     mode='''min'''	,     save_top_k=1   )
     if early_stopping_callback:
        extra_callbacks.append(__lowerCAmelCase   )
     if logging_callback is None:
        SCREAMING_SNAKE_CASE__			:				List[str]       						= LoggingCallback()
  
     SCREAMING_SNAKE_CASE__			:				str       						= {}
  
     # TODO: remove with PyTorch 1.6 since pl uses native amp
     if args.fpaa:
        SCREAMING_SNAKE_CASE__			:				Union[str, Any]       						= 16
        SCREAMING_SNAKE_CASE__			:				List[str]       						= args.fpaa_opt_level
  
     if args.gpus > 1:
        SCREAMING_SNAKE_CASE__			:				Optional[int]       						= "ddp"
  
     SCREAMING_SNAKE_CASE__			:				int       						= args.accumulate_grad_batches
     SCREAMING_SNAKE_CASE__			:				int       						= extra_train_kwargs.get('''accelerator'''	,     __lowerCAmelCase   )
     SCREAMING_SNAKE_CASE__			:				List[Any]       						= extra_train_kwargs.get('''profiler'''	,     __lowerCAmelCase   )
  
     SCREAMING_SNAKE_CASE__			:				Optional[Any]       						= pl.Trainer.from_argparse_args(
         __lowerCAmelCase	,     weights_summary=__lowerCAmelCase	,     callbacks=[logging_callback] + extra_callbacks	,     logger=__lowerCAmelCase	,     checkpoint_callback=__lowerCAmelCase	,     **__lowerCAmelCase	,     )
  
     if args.do_train:
        trainer.fit(__lowerCAmelCase   )
  
     return trainer
  
  
style_context: 
  
  
  
  
  '''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:
         lowercase__			=	False
  
  
  if is_vision_available():
         from PIL import Image
  else:
  
  
  
  
  
  
         class 						lowercase     :
  
  
  
  
  
  
               @staticmethod
               def    A__(*a__ ,  **a__					)       ->   Optional[Any]:
                  pass
  
  
  
  
  
  
  @is_pipeline_test
  @require_vision
  class 						lowercase     (   unittest.TestCase):
        __lowercase 		=  MODEL_FOR_VISION_2_SEQ_MAPPING
        __lowercase 		=  TF_MODEL_FOR_VISION_2_SEQ_MAPPING
  
  
  
  
  
  
        def    A__(self ,  a__ ,  a__ ,  a__					)       ->   Optional[Any]:
           SCREAMING_SNAKE_CASE__			:				Tuple       						= pipeline('''image-to-text''' ,  model=a__ ,  tokenizer=a__ ,  image_processor=a__					)
           SCREAMING_SNAKE_CASE__			:				List[Any]       						= [
               Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''					),
               '''./tests/fixtures/tests_samples/COCO/000000039769.png''',
           ]
           return pipe, examples
  
  
  
  
  
  
        def    A__(self ,  a__ ,  a__					)       ->   Any:
           SCREAMING_SNAKE_CASE__			:				Tuple       						= pipe(a__					)
           self.assertEqual(
               a__ ,  [
                   [{'''generated_text''': ANY(a__					)}],
                   [{'''generated_text''': ANY(a__					)}],
               ] ,  )
  
  
  
  
  
  
        @require_tf
        def    A__(self					)       ->   List[str]:
           SCREAMING_SNAKE_CASE__			:				List[str]       						= pipeline('''image-to-text''' ,  model='''hf-internal-testing/tiny-random-vit-gpt2''' ,  framework='''tf'''					)
           SCREAMING_SNAKE_CASE__			:				Union[str, Any]       						= '''./tests/fixtures/tests_samples/COCO/000000039769.png'''
  
           SCREAMING_SNAKE_CASE__			:				str       						= pipe(a__					)
           self.assertEqual(
               a__ ,  [
                   {
                       '''generated_text''': '''growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO'''
                   },
               ] ,  )
  
           SCREAMING_SNAKE_CASE__			:				Optional[Any]       						= pipe([image, image]					)
           self.assertEqual(
               a__ ,  [
                   [
                       {
                           '''generated_text''': '''growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO'''
                       }
                   ],
                   [
                       {
                           '''generated_text''': '''growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO'''
                       }
                   ],
               ] ,  )
  
           SCREAMING_SNAKE_CASE__			:				Union[str, Any]       						= pipe(a__ ,  max_new_tokens=1					)
           self.assertEqual(
               a__ ,  [{'''generated_text''': '''growth'''}] ,  )
  
  
  
  
  
  
        @require_torch
        def    A__(self					)       ->   Optional[Any]:
           SCREAMING_SNAKE_CASE__			:				Optional[int]       						= pipeline('''image-to-text''' ,  model='''hf-internal-testing/tiny-random-vit-gpt2'''					)
           SCREAMING_SNAKE_CASE__			:				Any       						= '''./tests/fixtures/tests_samples/COCO/000000039769.png'''
  
           SCREAMING_SNAKE_CASE__			:				Optional[Any]       						= pipe(a__					)
           self.assertEqual(
               a__ ,  [
                   {
                       '''generated_text''': '''growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO'''
                   },
               ] ,  )
  
           SCREAMING_SNAKE_CASE__			:				Any       						= pipe([image, image]					)
           self.assertEqual(
               a__ ,  [
                   [
                       {
                           '''generated_text''': '''growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO'''
                       }
                   ],
                   [
                       {
                           '''generated_text''': '''growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO'''
                       }
                   ],
               ] ,  )
  
  
  
  
  
  
        @require_torch
        def    A__(self					)       ->   Any:
           SCREAMING_SNAKE_CASE__			:				Union[str, Any]       						= pipeline('''image-to-text''' ,  model='''hf-internal-testing/tiny-random-BlipForConditionalGeneration'''					)
           SCREAMING_SNAKE_CASE__			:				int       						= '''./tests/fixtures/tests_samples/COCO/000000039769.png'''
           SCREAMING_SNAKE_CASE__			:				Tuple       						= '''a photo of'''
  
           SCREAMING_SNAKE_CASE__			:				List[Any]       						= pipe(a__ ,  prompt=a__					)
           self.assertTrue(outputs[0]['''generated_text'''].startswith(a__					)					)
  
  
  
  
  
  
        @slow
        @require_torch
        def    A__(self					)       ->   List[Any]:
           SCREAMING_SNAKE_CASE__			:				Tuple       						= pipeline('''image-to-text''' ,  model='''ydshieh/vit-gpt2-coco-en'''					)
           SCREAMING_SNAKE_CASE__			:				List[str]       						= '''./tests/fixtures/tests_samples/COCO/000000039769.png'''
  
           SCREAMING_SNAKE_CASE__			:				List[Any]       						= pipe(a__					)
           self.assertEqual(a__ ,  [{'''generated_text''': '''a cat laying on a blanket next to a cat laying on a bed '''}]					)
  
           SCREAMING_SNAKE_CASE__			:				Tuple       						= 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    A__(self					)       ->   Tuple:
           SCREAMING_SNAKE_CASE__			:				Dict       						= pipeline('''image-to-text''' ,  model='''Salesforce/blip-image-captioning-base'''					)
           SCREAMING_SNAKE_CASE__			:				Optional[Any]       						= '''https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/pokemon.png'''
           SCREAMING_SNAKE_CASE__			:				Optional[int]       						= Image.open(requests.get(a__ ,  stream=a__					).raw					)
  
           SCREAMING_SNAKE_CASE__			:				Optional[int]       						= pipe(a__					)
           self.assertEqual(a__ ,  [{'''generated_text''': '''a pink pokemon pokemon with a blue shirt and a blue shirt'''}]					)
  
  
  
  
  
  
        @slow
        @require_torch
        def    A__(self					)       ->   int:
           SCREAMING_SNAKE_CASE__			:				Optional[Any]       						= pipeline('''image-to-text''' ,  model='''microsoft/git-base-coco'''					)
           SCREAMING_SNAKE_CASE__			:				str       						= '''https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/pokemon.png'''
           SCREAMING_SNAKE_CASE__			:				List[str]       						= Image.open(requests.get(a__ ,  stream=a__					).raw					)
  
           SCREAMING_SNAKE_CASE__			:				str       						= pipe(a__					)
           self.assertEqual(a__ ,  [{'''generated_text''': '''a cartoon of a purple character.'''}]					)
  
  
  
  
  
  
        @slow
        @require_torch
        def    A__(self					)       ->   Dict:
           SCREAMING_SNAKE_CASE__			:				str       						= pipeline('''image-to-text''' ,  model='''Salesforce/blip-image-captioning-base'''					)
           SCREAMING_SNAKE_CASE__			:				List[Any]       						= '''https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg'''
           SCREAMING_SNAKE_CASE__			:				Optional[int]       						= Image.open(requests.get(a__ ,  stream=a__					).raw					)
  
           SCREAMING_SNAKE_CASE__			:				Union[str, Any]       						= '''a photography of'''
  
           SCREAMING_SNAKE_CASE__			:				Union[str, Any]       						= pipe(a__ ,  prompt=a__					)
           self.assertEqual(a__ ,  [{'''generated_text''': '''a photography of a volcano'''}]					)
  
           with self.assertRaises(a__					):
              SCREAMING_SNAKE_CASE__			:				Any       						= pipe([image, image] ,  prompt=[prompt, prompt]					)
  
  
  
  
  
  
        @slow
        @require_torch
        def    A__(self					)       ->   Dict:
           SCREAMING_SNAKE_CASE__			:				Union[str, Any]       						= pipeline('''image-to-text''' ,  model='''microsoft/git-base-coco'''					)
           SCREAMING_SNAKE_CASE__			:				Optional[int]       						= '''https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg'''
           SCREAMING_SNAKE_CASE__			:				Dict       						= Image.open(requests.get(a__ ,  stream=a__					).raw					)
  
           SCREAMING_SNAKE_CASE__			:				Optional[int]       						= '''a photo of a'''
  
           SCREAMING_SNAKE_CASE__			:				str       						= 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__					):
              SCREAMING_SNAKE_CASE__			:				Dict       						= 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					)       ->   Union[str, Any]:
           SCREAMING_SNAKE_CASE__			:				List[str]       						= pipeline('''image-to-text''' ,  model='''google/pix2struct-ai2d-base'''					)
           SCREAMING_SNAKE_CASE__			:				int       						= '''https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg'''
           SCREAMING_SNAKE_CASE__			:				Any       						= Image.open(requests.get(a__ ,  stream=a__					).raw					)
  
           SCREAMING_SNAKE_CASE__			:				int       						= '''What does the label 15 represent? (1) lava (2) core (3) tunnel (4) ash cloud'''
  
           SCREAMING_SNAKE_CASE__			:				Union[str, Any]       						= pipe(a__ ,  prompt=a__					)
           self.assertEqual(a__ ,  [{'''generated_text''': '''ash cloud'''}]					)
  
           with self.assertRaises(a__					):
              SCREAMING_SNAKE_CASE__			:				Any       						= pipe([image, image] ,  prompt=[prompt, prompt]					)
  
  
  
  
  
  
        @slow
        @require_tf
        def    A__(self					)       ->   str:
           SCREAMING_SNAKE_CASE__			:				Optional[int]       						= pipeline('''image-to-text''' ,  model='''ydshieh/vit-gpt2-coco-en''' ,  framework='''tf'''					)
           SCREAMING_SNAKE_CASE__			:				Optional[Any]       						= '''./tests/fixtures/tests_samples/COCO/000000039769.png'''
  
           SCREAMING_SNAKE_CASE__			:				Dict       						= pipe(a__					)
           self.assertEqual(a__ ,  [{'''generated_text''': '''a cat laying on a blanket next to a cat laying on a bed '''}]					)
  
           SCREAMING_SNAKE_CASE__			:				Union[str, Any]       						= 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 '''}],
               ] ,  )
  
  