

'''simple docstring'''

import random
import unittest

import numpy as np

import transformers
from transformers import is_flax_available, is_torch_available
from transformers.testing_utils import is_pt_flax_cross_test, require_flax


if is_flax_available():
				import os

				import jax.numpy as jnp
				from jax import jit

				from transformers import AutoTokenizer, FlaxAutoModelForCausalLM
				from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model

				a   :			Optional[int]         = '''0.12'''  # assumed parallelism: 8


if is_torch_available():
				import torch





def       lowercase					(     __magic_name__ ,    __magic_name__ ,    __magic_name__=None							):



					'''simple docstring'''







					if rng is None:
										UpperCAmelCase		:							str   					=   random.Random()

					UpperCAmelCase		:							str   					=   1
					for dim in shape:
										total_dims *= dim

					UpperCAmelCase		:							Dict   					=   []
					for _ in range(__UpperCamelCase							):
										values.append(rng.randint(0 ,    vocab_size - 1							)							)

					UpperCAmelCase		:							int   					=   np.array(__UpperCamelCase ,    dtype=jnp.intaa							).reshape(__UpperCamelCase							)

					return output





def       lowercase					(     __magic_name__ ,    __magic_name__=None							):



					'''simple docstring'''







					UpperCAmelCase		:							Dict   					=   ids_tensor(__UpperCamelCase ,    vocab_size=2 ,    rng=__UpperCamelCase							)
					# make sure that at least one token is attended to for each batch
					UpperCAmelCase		:							Optional[int]   					=   1
					return attn_mask







@require_flax
class   UpperCamelCase__    :


		"""simple docstring"""

		SCREAMING_SNAKE_CASE__  :	List[Any]   =							None
		SCREAMING_SNAKE_CASE__  :	List[Any]   =							()







		def       A_       ( self			):


							'''simple docstring'''

							UpperCAmelCase					, UpperCAmelCase		:							Dict   					=   self.model_tester.prepare_config_and_inputs_for_common()

							# cut to half length & take max batch_size 3
							UpperCAmelCase		:							Tuple   					=   2
							UpperCAmelCase		:							Optional[int]   					=   inputs["input_ids"].shape[-1] // 2
							UpperCAmelCase		:							Optional[int]   					=   inputs["input_ids"][:max_batch_size, :sequence_length]

							UpperCAmelCase		:							Any   					=   jnp.ones_like(_lowercase			)
							UpperCAmelCase		:							List[str]   					=   attention_mask[:max_batch_size, :sequence_length]

							# generate max 5 tokens
							UpperCAmelCase		:							Tuple   					=   input_ids.shape[-1] + 5
							if config.eos_token_id is not None and config.pad_token_id is None:
												# hack to allow generate for models such as GPT2 as is done in `generate()`
												UpperCAmelCase		:							Optional[int]   					=   config.eos_token_id
							return config, input_ids, attention_mask, max_length







		@is_pt_flax_cross_test
		def       A_       ( self			):


							'''simple docstring'''

							UpperCAmelCase					, UpperCAmelCase					, UpperCAmelCase					, UpperCAmelCase		:							List[Any]   					=   self._get_input_ids_and_config()
							UpperCAmelCase		:							str   					=   False
							UpperCAmelCase		:							Dict   					=   max_length
							UpperCAmelCase		:							Any   					=   0

							for model_class in self.all_generative_model_classes:
												UpperCAmelCase		:							Union[str, Any]   					=   model_class(_lowercase			)

												UpperCAmelCase		:							str   					=   model_class.__name__[4:]  # Skip the "Flax" at the beginning
												UpperCAmelCase		:							Optional[Any]   					=   getattr(_lowercase    ,			_lowercase			)
												UpperCAmelCase		:							str   					=   pt_model_class(_lowercase			).eval()
												UpperCAmelCase		:							Optional[Any]   					=   load_flax_weights_in_pytorch_model(_lowercase    ,			flax_model.params			)

												UpperCAmelCase		:							List[str]   					=   flax_model.generate(_lowercase			).sequences
												UpperCAmelCase		:							Dict   					=   pt_model.generate(torch.tensor(_lowercase    ,			dtype=torch.long			)			)

												if flax_generation_outputs.shape[-1] > pt_generation_outputs.shape[-1]:
																	UpperCAmelCase		:							List[Any]   					=   flax_generation_outputs[:, : pt_generation_outputs.shape[-1]]

												self.assertListEqual(pt_generation_outputs.numpy().tolist()    ,			flax_generation_outputs.tolist()			)







		def       A_       ( self			):


							'''simple docstring'''

							UpperCAmelCase					, UpperCAmelCase					, UpperCAmelCase					, UpperCAmelCase		:							Optional[Any]   					=   self._get_input_ids_and_config()
							UpperCAmelCase		:							List[Any]   					=   False
							UpperCAmelCase		:							Union[str, Any]   					=   max_length

							for model_class in self.all_generative_model_classes:
												UpperCAmelCase		:							List[Any]   					=   model_class(_lowercase			)

												UpperCAmelCase		:							Optional[int]   					=   model.generate(_lowercase			).sequences
												self.assertEqual(generation_outputs.shape[-1]    ,			_lowercase			)

												UpperCAmelCase		:							str   					=   jit(model.generate			)
												UpperCAmelCase		:							Tuple   					=   jit_generate(_lowercase			).sequences

												self.assertListEqual(generation_outputs.tolist()    ,			jit_generation_outputs.tolist()			)







		def       A_       ( self			):


							'''simple docstring'''

							UpperCAmelCase					, UpperCAmelCase					, UpperCAmelCase					, UpperCAmelCase		:							Optional[Any]   					=   self._get_input_ids_and_config()
							UpperCAmelCase		:							Dict   					=   True
							UpperCAmelCase		:							Tuple   					=   max_length

							for model_class in self.all_generative_model_classes:
												UpperCAmelCase		:							Union[str, Any]   					=   model_class(_lowercase			)

												UpperCAmelCase		:							Any   					=   model.generate(_lowercase			).sequences
												self.assertEqual(generation_outputs.shape[-1]    ,			_lowercase			)

												UpperCAmelCase		:							str   					=   jit(model.generate			)
												UpperCAmelCase		:							List[Any]   					=   jit_generate(_lowercase			).sequences

												self.assertListEqual(generation_outputs.tolist()    ,			jit_generation_outputs.tolist()			)







		def       A_       ( self			):


							'''simple docstring'''

							UpperCAmelCase					, UpperCAmelCase					, UpperCAmelCase					, UpperCAmelCase		:							Union[str, Any]   					=   self._get_input_ids_and_config()
							UpperCAmelCase		:							List[Any]   					=   False
							UpperCAmelCase		:							int   					=   max_length
							UpperCAmelCase		:							Union[str, Any]   					=   2

							for model_class in self.all_generative_model_classes:
												UpperCAmelCase		:							List[Any]   					=   model_class(_lowercase			)

												UpperCAmelCase		:							Any   					=   model.generate(_lowercase			).sequences
												self.assertEqual(generation_outputs.shape[-1]    ,			_lowercase			)

												UpperCAmelCase		:							str   					=   jit(model.generate			)
												UpperCAmelCase		:							Optional[Any]   					=   jit_generate(_lowercase			).sequences

												self.assertListEqual(generation_outputs.tolist()    ,			jit_generation_outputs.tolist()			)







		def       A_       ( self			):


							'''simple docstring'''

							UpperCAmelCase					, UpperCAmelCase					, UpperCAmelCase					, UpperCAmelCase		:							Union[str, Any]   					=   self._get_input_ids_and_config()
							UpperCAmelCase		:							Union[str, Any]   					=   False
							UpperCAmelCase		:							List[str]   					=   max_length
							UpperCAmelCase		:							Optional[Any]   					=   2
							UpperCAmelCase		:							Optional[Any]   					=   2

							for model_class in self.all_generative_model_classes:
												UpperCAmelCase		:							Tuple   					=   model_class(_lowercase			)

												UpperCAmelCase		:							List[Any]   					=   model.generate(_lowercase			).sequences
												self.assertEqual(generation_outputs.shape[0]    ,			input_ids.shape[0] * config.num_return_sequences			)







		def       A_       ( self			):


							'''simple docstring'''

							UpperCAmelCase					, UpperCAmelCase					, UpperCAmelCase					, UpperCAmelCase		:							Any   					=   self._get_input_ids_and_config()
							UpperCAmelCase		:							List[Any]   					=   True
							UpperCAmelCase		:							List[Any]   					=   max_length
							UpperCAmelCase		:							List[str]   					=   0.8
							UpperCAmelCase		:							List[str]   					=   1_0
							UpperCAmelCase		:							Any   					=   0.3
							UpperCAmelCase		:							Union[str, Any]   					=   1
							UpperCAmelCase		:							Union[str, Any]   					=   8
							UpperCAmelCase		:							List[Any]   					=   9

							for model_class in self.all_generative_model_classes:
												UpperCAmelCase		:							List[str]   					=   model_class(_lowercase			)

												UpperCAmelCase		:							Optional[Any]   					=   model.generate(_lowercase			).sequences
												self.assertEqual(generation_outputs.shape[-1]    ,			_lowercase			)

												UpperCAmelCase		:							int   					=   jit(model.generate			)
												UpperCAmelCase		:							Tuple   					=   jit_generate(_lowercase			).sequences

												self.assertListEqual(generation_outputs.tolist()    ,			jit_generation_outputs.tolist()			)







		def       A_       ( self			):


							'''simple docstring'''

							UpperCAmelCase					, UpperCAmelCase					, UpperCAmelCase					, UpperCAmelCase		:							Tuple   					=   self._get_input_ids_and_config()
							UpperCAmelCase		:							Optional[Any]   					=   max_length
							UpperCAmelCase		:							Dict   					=   1
							UpperCAmelCase		:							Optional[Any]   					=   8
							UpperCAmelCase		:							List[Any]   					=   9

							for model_class in self.all_generative_model_classes:
												UpperCAmelCase		:							Optional[int]   					=   model_class(_lowercase			)

												UpperCAmelCase		:							Dict   					=   model.generate(_lowercase			).sequences
												self.assertEqual(generation_outputs.shape[-1]    ,			_lowercase			)

												UpperCAmelCase		:							Dict   					=   jit(model.generate			)
												UpperCAmelCase		:							Union[str, Any]   					=   jit_generate(_lowercase			).sequences

												self.assertListEqual(generation_outputs.tolist()    ,			jit_generation_outputs.tolist()			)







		def       A_       ( self			):


							'''simple docstring'''

							UpperCAmelCase					, UpperCAmelCase					, UpperCAmelCase					, UpperCAmelCase		:							List[Any]   					=   self._get_input_ids_and_config()
							UpperCAmelCase		:							Optional[int]   					=   max_length
							UpperCAmelCase		:							Tuple   					=   2
							UpperCAmelCase		:							int   					=   1
							UpperCAmelCase		:							str   					=   8
							UpperCAmelCase		:							Any   					=   9

							for model_class in self.all_generative_model_classes:
												UpperCAmelCase		:							Union[str, Any]   					=   model_class(_lowercase			)

												UpperCAmelCase		:							List[str]   					=   model.generate(_lowercase			).sequences
												self.assertEqual(generation_outputs.shape[-1]    ,			_lowercase			)

												UpperCAmelCase		:							List[Any]   					=   jit(model.generate			)
												UpperCAmelCase		:							Union[str, Any]   					=   jit_generate(_lowercase			).sequences

												self.assertListEqual(generation_outputs.tolist()    ,			jit_generation_outputs.tolist()			)







		def       A_       ( self			):


							'''simple docstring'''

							UpperCAmelCase					, UpperCAmelCase					, UpperCAmelCase					, UpperCAmelCase		:							List[str]   					=   self._get_input_ids_and_config()

							# pad attention mask on the left
							UpperCAmelCase		:							int   					=   attention_mask.at[(0, 0)].set(0			)

							UpperCAmelCase		:							str   					=   False
							UpperCAmelCase		:							Dict   					=   max_length

							for model_class in self.all_generative_model_classes:
												UpperCAmelCase		:							List[str]   					=   model_class(_lowercase			)

												UpperCAmelCase		:							Any   					=   model.generate(_lowercase    ,			attention_mask=_lowercase			).sequences
												self.assertEqual(generation_outputs.shape[-1]    ,			_lowercase			)

												UpperCAmelCase		:							Dict   					=   jit(model.generate			)
												UpperCAmelCase		:							str   					=   jit_generate(_lowercase    ,			attention_mask=_lowercase			).sequences

												self.assertListEqual(generation_outputs.tolist()    ,			jit_generation_outputs.tolist()			)







		def       A_       ( self			):


							'''simple docstring'''

							UpperCAmelCase					, UpperCAmelCase					, UpperCAmelCase					, UpperCAmelCase		:							Tuple   					=   self._get_input_ids_and_config()

							# pad attention mask on the left
							UpperCAmelCase		:							Optional[Any]   					=   attention_mask.at[(0, 0)].set(0			)

							UpperCAmelCase		:							List[Any]   					=   True
							UpperCAmelCase		:							Dict   					=   max_length

							for model_class in self.all_generative_model_classes:
												UpperCAmelCase		:							List[Any]   					=   model_class(_lowercase			)

												UpperCAmelCase		:							Any   					=   model.generate(_lowercase    ,			attention_mask=_lowercase			).sequences
												self.assertEqual(generation_outputs.shape[-1]    ,			_lowercase			)

												UpperCAmelCase		:							Dict   					=   jit(model.generate			)
												UpperCAmelCase		:							Union[str, Any]   					=   jit_generate(_lowercase    ,			attention_mask=_lowercase			).sequences

												self.assertListEqual(generation_outputs.tolist()    ,			jit_generation_outputs.tolist()			)







		def       A_       ( self			):


							'''simple docstring'''

							UpperCAmelCase					, UpperCAmelCase					, UpperCAmelCase					, UpperCAmelCase		:							Tuple   					=   self._get_input_ids_and_config()

							# pad attention mask on the left
							UpperCAmelCase		:							Dict   					=   attention_mask.at[(0, 0)].set(0			)

							UpperCAmelCase		:							Dict   					=   2
							UpperCAmelCase		:							Union[str, Any]   					=   max_length

							for model_class in self.all_generative_model_classes:
												UpperCAmelCase		:							Dict   					=   model_class(_lowercase			)

												UpperCAmelCase		:							Dict   					=   model.generate(_lowercase    ,			attention_mask=_lowercase			).sequences
												self.assertEqual(generation_outputs.shape[-1]    ,			_lowercase			)

												UpperCAmelCase		:							Optional[Any]   					=   jit(model.generate			)
												UpperCAmelCase		:							int   					=   jit_generate(_lowercase    ,			attention_mask=_lowercase			).sequences

												self.assertListEqual(generation_outputs.tolist()    ,			jit_generation_outputs.tolist()			)







@require_flax
class   UpperCamelCase__    (   unittest.TestCase   ):


		"""simple docstring"""

		def       A_       ( self			):


							'''simple docstring'''

							UpperCAmelCase		:							int   					=   AutoTokenizer.from_pretrained("hf-internal-testing/tiny-bert"			)
							UpperCAmelCase		:							Any   					=   FlaxAutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-bert-flax-only"			)

							UpperCAmelCase		:							Optional[int]   					=   "Hello world"
							UpperCAmelCase		:							Optional[int]   					=   tokenizer(_lowercase    ,			return_tensors="np"			).input_ids

							# typos are quickly detected (the correct argument is `do_sample`)
							with self.assertRaisesRegex(_lowercase    ,			"do_samples"			):
												model.generate(_lowercase    ,			do_samples=_lowercase			)

							# arbitrary arguments that will not be used anywhere are also not accepted
							with self.assertRaisesRegex(_lowercase    ,			"foo"			):
												UpperCAmelCase		:							Optional[Any]   					=   {"foo": "bar"}
												model.generate(_lowercase    ,			**_lowercase			)

# 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 __snake_case				(						lowerCamelCase_		):
   lowerCAmelCase_														=							"Salesforce/blip-image-captioning-base"
   lowerCAmelCase_														=							(
       "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."
   )
   lowerCAmelCase_														=							"image_captioner"
   lowerCAmelCase_														=							AutoModelForVisionaSeq

   lowerCAmelCase_														=							["image"]
   lowerCAmelCase_														=							["text"]




   def __init__(    self			:				List[Any]       ,	*_lowercase			:				Optional[int]       ,	**_lowercase			:				Union[str, Any]      ):



     """simple docstring"""






     requires_backends(self       ,	["""vision"""]      )
     super().__init__(*_lowercase       ,	**_lowercase      )




   def 	__a						(    self			:				Tuple       ,	_lowercase			:				"Image"      ):



     """simple docstring"""






     return self.pre_processor(images=_lowercase       ,	return_tensors="""pt"""      )




   def 	__a						(    self			:				Union[str, Any]       ,	_lowercase			:				Optional[int]      ):



     """simple docstring"""






     return self.model.generate(**_lowercase      )




   def 	__a						(    self			:				int       ,	_lowercase			:				Any      ):



     """simple docstring"""






     return self.pre_processor.batch_decode(_lowercase       ,	skip_special_tokens=_lowercase      )[0].strip()
