






"""simple docstring"""


import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
		import torch

		from transformers import (
		    OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST,
		    OpenAIGPTConfig,
		    OpenAIGPTDoubleHeadsModel,
		    OpenAIGPTForSequenceClassification,
		    OpenAIGPTLMHeadModel,
		    OpenAIGPTModel,
		)




class 						__UpperCamelCase     :
					def __init__(							self							:	Any     , UpperCAmelCase							:	List[Any]     , UpperCAmelCase							:	Any=13     , UpperCAmelCase							:	List[str]=7     , UpperCAmelCase							:	Dict=True     , UpperCAmelCase							:	Dict=True     , UpperCAmelCase							:	int=True     , UpperCAmelCase							:	str=99     , UpperCAmelCase							:	List[str]=32     , UpperCAmelCase							:	List[Any]=5     , UpperCAmelCase							:	List[str]=4     , UpperCAmelCase							:	Optional[int]=37     , UpperCAmelCase							:	Union[str, Any]="gelu"     , UpperCAmelCase							:	int=0.1     , UpperCAmelCase							:	Any=0.1     , UpperCAmelCase							:	Optional[Any]=512     , UpperCAmelCase							:	List[str]=16     , UpperCAmelCase							:	Any=2     , UpperCAmelCase							:	Tuple=0.0_2     , UpperCAmelCase							:	str=3     , UpperCAmelCase							:	int=4     , UpperCAmelCase							:	int=None     , )	->       str:
											lowerCAmelCase   :Union[str, Any]						=			parent
											lowerCAmelCase   :Optional[int]						=			batch_size
											lowerCAmelCase   :Optional[int]						=			seq_length
											lowerCAmelCase   :Optional[int]						=			is_training
											lowerCAmelCase   :Optional[Any]						=			use_token_type_ids
											lowerCAmelCase   :Optional[Any]						=			use_labels
											lowerCAmelCase   :Optional[Any]						=			vocab_size
											lowerCAmelCase   :Optional[Any]						=			hidden_size
											lowerCAmelCase   :List[Any]						=			num_hidden_layers
											lowerCAmelCase   :Optional[int]						=			num_attention_heads
											lowerCAmelCase   :Optional[Any]						=			intermediate_size
											lowerCAmelCase   :List[str]						=			hidden_act
											lowerCAmelCase   :Tuple						=			hidden_dropout_prob
											lowerCAmelCase   :Optional[int]						=			attention_probs_dropout_prob
											lowerCAmelCase   :Optional[Any]						=			max_position_embeddings
											lowerCAmelCase   :Any						=			type_vocab_size
											lowerCAmelCase   :List[Any]						=			type_sequence_label_size
											lowerCAmelCase   :int						=			initializer_range
											lowerCAmelCase   :str						=			num_labels
											lowerCAmelCase   :int						=			num_choices
											lowerCAmelCase   :List[Any]						=			scope
											lowerCAmelCase   :Dict						=			self.vocab_size - 1
					def        UpperCAmelCase__ (							self							:	List[str]   )	->       str:
											lowerCAmelCase   :Tuple						=			ids_tensor([self.batch_size, self.seq_length]     , self.vocab_size   )

											lowerCAmelCase   :Optional[Any]						=			None
											if self.use_token_type_ids:
																	lowerCAmelCase   :List[Any]						=			ids_tensor([self.batch_size, self.seq_length]     , self.type_vocab_size   )

											lowerCAmelCase   :Any						=			None
											lowerCAmelCase   :Optional[int]						=			None
											lowerCAmelCase   :Optional[Any]						=			None
											if self.use_labels:
																	lowerCAmelCase   :Optional[Any]						=			ids_tensor([self.batch_size]     , self.type_sequence_label_size   )
																	lowerCAmelCase   :Tuple						=			ids_tensor([self.batch_size, self.seq_length]     , self.num_labels   )
																	lowerCAmelCase   :List[Any]						=			ids_tensor([self.batch_size]     , self.num_choices   )

											lowerCAmelCase   :Optional[int]						=			OpenAIGPTConfig(
											    vocab_size=self.vocab_size     , n_embd=self.hidden_size     , n_layer=self.num_hidden_layers     , n_head=self.num_attention_heads     , n_positions=self.max_position_embeddings     , pad_token_id=self.pad_token_id     , )

											lowerCAmelCase   :Any						=			ids_tensor([self.num_hidden_layers, self.num_attention_heads]     , 2   )

											return (
											    config,
											    input_ids,
											    head_mask,
											    token_type_ids,
											    sequence_labels,
											    token_labels,
											    choice_labels,
											)
					def        UpperCAmelCase__ (							self							:	Tuple     , UpperCAmelCase							:	Dict     , UpperCAmelCase							:	Optional[Any]     , UpperCAmelCase							:	Optional[Any]     , UpperCAmelCase							:	Tuple     , *UpperCAmelCase							:	int   )	->       List[str]:
											lowerCAmelCase   :str						=			OpenAIGPTModel(config=UpperCAmelCase   )
											model.to(UpperCAmelCase   )
											model.eval()

											lowerCAmelCase   :Optional[Any]						=			model(UpperCAmelCase     , token_type_ids=UpperCAmelCase     , head_mask=UpperCAmelCase   )
											lowerCAmelCase   :Optional[int]						=			model(UpperCAmelCase     , token_type_ids=UpperCAmelCase   )
											lowerCAmelCase   :Union[str, Any]						=			model(UpperCAmelCase   )

											self.parent.assertEqual(result.last_hidden_state.shape     , (self.batch_size, self.seq_length, self.hidden_size)   )
					def        UpperCAmelCase__ (							self							:	List[str]     , UpperCAmelCase							:	int     , UpperCAmelCase							:	List[str]     , UpperCAmelCase							:	Optional[Any]     , UpperCAmelCase							:	List[Any]     , *UpperCAmelCase							:	str   )	->       Optional[int]:
											lowerCAmelCase   :Optional[Any]						=			OpenAIGPTLMHeadModel(UpperCAmelCase   )
											model.to(UpperCAmelCase   )
											model.eval()

											lowerCAmelCase   :int						=			model(UpperCAmelCase     , token_type_ids=UpperCAmelCase     , labels=UpperCAmelCase   )
											self.parent.assertEqual(result.loss.shape     , ()   )
											self.parent.assertEqual(result.logits.shape     , (self.batch_size, self.seq_length, self.vocab_size)   )
					def        UpperCAmelCase__ (							self							:	List[str]     , UpperCAmelCase							:	List[str]     , UpperCAmelCase							:	str     , UpperCAmelCase							:	Optional[int]     , UpperCAmelCase							:	List[str]     , *UpperCAmelCase							:	Optional[Any]   )	->       List[Any]:
											lowerCAmelCase   :Union[str, Any]						=			OpenAIGPTDoubleHeadsModel(UpperCAmelCase   )
											model.to(UpperCAmelCase   )
											model.eval()

											lowerCAmelCase   :Tuple						=			model(UpperCAmelCase     , token_type_ids=UpperCAmelCase     , labels=UpperCAmelCase   )
											self.parent.assertEqual(result.loss.shape     , ()   )
											self.parent.assertEqual(result.logits.shape     , (self.batch_size, self.seq_length, self.vocab_size)   )
					def        UpperCAmelCase__ (							self							:	Union[str, Any]     , UpperCAmelCase							:	Optional[int]     , UpperCAmelCase							:	Dict     , UpperCAmelCase							:	Union[str, Any]     , UpperCAmelCase							:	Tuple     , *UpperCAmelCase							:	Tuple   )	->       List[Any]:
											lowerCAmelCase   :Union[str, Any]						=			self.num_labels
											lowerCAmelCase   :Optional[int]						=			OpenAIGPTForSequenceClassification(UpperCAmelCase   )
											model.to(UpperCAmelCase   )
											model.eval()

											lowerCAmelCase   :Dict						=			ids_tensor([self.batch_size]     , self.type_sequence_label_size   )
											lowerCAmelCase   :List[str]						=			model(UpperCAmelCase     , token_type_ids=UpperCAmelCase     , labels=UpperCAmelCase   )
											self.parent.assertEqual(result.logits.shape     , (self.batch_size, self.num_labels)   )
					def        UpperCAmelCase__ (							self							:	Any   )	->       int:
											lowerCAmelCase   :Optional[Any]						=			self.prepare_config_and_inputs()
											(
											    (
											    lowerCAmelCase
											)	, (
											    lowerCAmelCase
											)	, (
											    lowerCAmelCase
											)	, (
											    lowerCAmelCase
											)	, (
											    lowerCAmelCase
											)	, (
											    lowerCAmelCase
											)	, (
											    lowerCAmelCase
											)	, 
											)   :Optional[Any]						=			config_and_inputs
											lowerCAmelCase   :Optional[int]						=			{
											    'input_ids': input_ids,
											    'token_type_ids': token_type_ids,
											    'head_mask': head_mask,
											}

											return config, inputs_dict




@require_torch
class 						__UpperCamelCase     (     UpperCamelCase   ,     UpperCamelCase   ,     UpperCamelCase   ,     unittest.TestCase						):
					lowercase_    :				Tuple      =  (
					    (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification)
					    if is_torch_available()
					    else ()
					)
					lowercase_    :				Optional[int]      =  (
					    (OpenAIGPTLMHeadModel,) if is_torch_available() else ()
					)  # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly
					lowercase_    :				List[str]      =  (
					    {
					        """feature-extraction""": OpenAIGPTModel,
					        """text-classification""": OpenAIGPTForSequenceClassification,
					        """text-generation""": OpenAIGPTLMHeadModel,
					        """zero-shot""": OpenAIGPTForSequenceClassification,
					    }
					    if is_torch_available()
					    else {}
					)
					def        UpperCAmelCase__ (							self							:	Dict     , UpperCAmelCase							:	Tuple     , UpperCAmelCase							:	int     , UpperCAmelCase							:	List[str]     , UpperCAmelCase							:	Optional[int]     , UpperCAmelCase							:	Union[str, Any]   )	->       str:
											if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
																	# Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
																	# `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a
																	# tiny config could not be created.
																	return True

											return False
					def        UpperCAmelCase__ (							self							:	Any     , UpperCAmelCase							:	Dict     , UpperCAmelCase							:	str     , UpperCAmelCase							:	Optional[Any]=False   )	->       Dict:
											lowerCAmelCase   :int						=			super()._prepare_for_class(UpperCAmelCase     , UpperCAmelCase     , return_labels=UpperCAmelCase   )

											if return_labels:
																	if model_class.__name__ == "OpenAIGPTDoubleHeadsModel":
																							lowerCAmelCase   :Optional[Any]						=			torch.zeros(
																							    (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length)     , dtype=torch.long     , device=UpperCAmelCase     , )
																							lowerCAmelCase   :Dict						=			inputs_dict['labels']
																							lowerCAmelCase   :Optional[int]						=			inputs_dict['labels']
																							lowerCAmelCase   :Dict						=			torch.zeros(
																							    (self.model_tester.batch_size, self.model_tester.num_choices)     , dtype=torch.long     , device=UpperCAmelCase     , )
																							lowerCAmelCase   :List[Any]						=			torch.zeros(
																							    self.model_tester.batch_size     , dtype=torch.long     , device=UpperCAmelCase   )
											return inputs_dict
					def        UpperCAmelCase__ (							self							:	Any   )	->       Any:
											lowerCAmelCase   :Optional[Any]						=			OpenAIGPTModelTester(self   )
											lowerCAmelCase   :Dict						=			ConfigTester(self     , config_class=UpperCAmelCase     , n_embd=37   )
					def        UpperCAmelCase__ (							self							:	str   )	->       int:
											self.config_tester.run_common_tests()
					def        UpperCAmelCase__ (							self							:	str   )	->       str:
											lowerCAmelCase   :str						=			self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_openai_gpt_model(*UpperCAmelCase   )
					def        UpperCAmelCase__ (							self							:	List[str]   )	->       int:
											lowerCAmelCase   :Optional[Any]						=			self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_lm_head_model(*UpperCAmelCase   )
					def        UpperCAmelCase__ (							self							:	List[Any]   )	->       Any:
											lowerCAmelCase   :str						=			self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_double_lm_head_model(*UpperCAmelCase   )
					def        UpperCAmelCase__ (							self							:	Dict   )	->       Optional[Any]:
											lowerCAmelCase   :List[Any]						=			self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*UpperCAmelCase   )
					@slow
					def        UpperCAmelCase__ (							self							:	Tuple   )	->       str:
											for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	lowerCAmelCase   :Dict						=			OpenAIGPTModel.from_pretrained(UpperCAmelCase   )
																	self.assertIsNotNone(UpperCAmelCase   )




@require_torch
class 						__UpperCamelCase     (     unittest.TestCase						):
					@slow
					def        UpperCAmelCase__ (							self							:	Optional[int]   )	->       List[Any]:
											lowerCAmelCase   :List[str]						=			OpenAIGPTLMHeadModel.from_pretrained('openai-gpt'   )
											model.to(UpperCAmelCase   )
											lowerCAmelCase   :Optional[int]						=			torch.tensor([[481, 4735, 544]]     , dtype=torch.long     , device=UpperCAmelCase   )  # the president is
											lowerCAmelCase   :Tuple						=			[
											    481,
											    4735,
											    544,
											    246,
											    963,
											    870,
											    762,
											    239,
											    244,
											    4_0477,
											    244,
											    249,
											    719,
											    881,
											    487,
											    544,
											    240,
											    244,
											    603,
											    481,
											]  # the president is a very good man. " \n " i\'m sure he is, " said the

											lowerCAmelCase   :Tuple						=			model.generate(UpperCAmelCase     , do_sample=UpperCAmelCase   )
											self.assertListEqual(output_ids[0].tolist()     , UpperCAmelCase   )







"""simple docstring"""


# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

from ..models.auto import AutoModelForVisionaSeq
from ..utils import requires_backends
from .base import PipelineTool


if TYPE_CHECKING:
		from PIL import Image




class 						__UpperCamelCase     (     UpperCamelCase						):
					lowercase_    :				Optional[Any]      =  """Salesforce/blip-image-captioning-base"""
					lowercase_    :				Optional[int]      =  (
					    """This is a tool that generates a description of an image. It takes an input named `image` which should be the """
					    """image to caption, and returns a text that contains the description in English."""
					)
					lowercase_    :				int      =  """image_captioner"""
					lowercase_    :				int      =  AutoModelForVisionaSeq

					lowercase_    :				List[str]      =  ["""image"""]
					lowercase_    :				int      =  ["""text"""]
					def __init__(							self							:	Any     , *UpperCAmelCase							:	str     , **UpperCAmelCase							:	List[str]   )	->       Union[str, Any]:
											requires_backends(self     , ['vision']   )
											super().__init__(*UpperCAmelCase     , **UpperCAmelCase   )
					def        UpperCAmelCase__ (							self							:	int     , UpperCAmelCase							:	"Image"   )	->       Union[str, Any]:
											return self.pre_processor(images=UpperCAmelCase     , return_tensors='pt'   )
					def        UpperCAmelCase__ (							self							:	int     , UpperCAmelCase							:	Optional[int]   )	->       Optional[int]:
											return self.model.generate(**UpperCAmelCase   )
					def        UpperCAmelCase__ (							self							:	Dict     , UpperCAmelCase							:	int   )	->       Dict:
											return self.pre_processor.batch_decode(UpperCAmelCase     , skip_special_tokens=UpperCAmelCase   )[0].strip()