




"""simple docstring"""






import unittest

import numpy as np
import timeout_decorator  # noqa

from transformers import BlenderbotConfig, is_flax_available
from transformers.testing_utils import jax_device, require_flax, slow

from ...generation.test_flax_utils import FlaxGenerationTesterMixin
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor


if is_flax_available():
			import os

			# The slow tests are often failing with OOM error on GPU
			# This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed
			# but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html
			lowercase__  		=		"""platform"""

			import jax
			import jax.numpy as jnp

			from transformers import BlenderbotTokenizer
			from transformers.models.blenderbot.modeling_flax_blenderbot import (
			    FlaxBlenderbotForConditionalGeneration,
			    FlaxBlenderbotModel,
			    shift_tokens_right,
			)







def   _snake_case    (       lowercase__							,					lowercase__							,					lowercase__=None							,					lowercase__=None							,					lowercase__=None							,					lowercase__=None							,					lowercase__=None							,					lowercase__=None							,					):



				if attention_mask is None:
								_lowerCamelCase  :    List[str]					=					np.where(input_ids != config.pad_token_id							,					1							,					0	)
				if decoder_attention_mask is None:
								_lowerCamelCase  :    Optional[int]					=					np.where(decoder_input_ids != config.pad_token_id							,					1							,					0	)
				if head_mask is None:
								_lowerCamelCase  :    Optional[Any]					=					np.ones((config.encoder_layers, config.encoder_attention_heads)	)
				if decoder_head_mask is None:
								_lowerCamelCase  :    Optional[int]					=					np.ones((config.decoder_layers, config.decoder_attention_heads)	)
				if cross_attn_head_mask is None:
								_lowerCamelCase  :    str					=					np.ones((config.decoder_layers, config.decoder_attention_heads)	)
				return {
				    "input_ids": input_ids,
				    "decoder_input_ids": decoder_input_ids,
				    "attention_mask": attention_mask,
				    "decoder_attention_mask": attention_mask,
				}






class lowerCAmelCase__			:






			'''simple docstring'''



			def __init__(						self						,   lowercase						,   lowercase=13						,   lowercase=7						,   lowercase=True						,   lowercase=False						,   lowercase=99						,   lowercase=16						,   lowercase=2						,   lowercase=4						,   lowercase=4						,   lowercase="gelu"						,   lowercase=0.1						,   lowercase=0.1						,   lowercase=32						,   lowercase=2						,   lowercase=1						,   lowercase=0						,   lowercase=0.02						,   ):
							_lowerCamelCase  :    Any					=					parent
							_lowerCamelCase  :    List[Any]					=					batch_size
							_lowerCamelCase  :    Any					=					seq_length
							_lowerCamelCase  :    str					=					is_training
							_lowerCamelCase  :    Any					=					use_labels
							_lowerCamelCase  :    List[Any]					=					vocab_size
							_lowerCamelCase  :    str					=					hidden_size
							_lowerCamelCase  :    int					=					num_hidden_layers
							_lowerCamelCase  :    Union[str, Any]					=					num_attention_heads
							_lowerCamelCase  :    Tuple					=					intermediate_size
							_lowerCamelCase  :    Tuple					=					hidden_act
							_lowerCamelCase  :    Tuple					=					hidden_dropout_prob
							_lowerCamelCase  :    str					=					attention_probs_dropout_prob
							_lowerCamelCase  :    List[str]					=					max_position_embeddings
							_lowerCamelCase  :    List[str]					=					eos_token_id
							_lowerCamelCase  :    Dict					=					pad_token_id
							_lowerCamelCase  :    Optional[Any]					=					bos_token_id
							_lowerCamelCase  :    Any					=					initializer_range
			def       A_					(						self						):
							_lowerCamelCase  :    str					=					np.clip(ids_tensor([self.batch_size, self.seq_length - 1]						,   self.vocab_size						)						,   3						,   self.vocab_size						)
							_lowerCamelCase  :    Dict					=					np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1)						,   dtype=np.intaa						))						,   -1						)

							_lowerCamelCase  :    Any					=					shift_tokens_right(lowerCamelCase_						,   1						,   2						)

							_lowerCamelCase  :    Tuple					=					BlenderbotConfig(
							    vocab_size=self.vocab_size						,   d_model=self.hidden_size						,   encoder_layers=self.num_hidden_layers						,   decoder_layers=self.num_hidden_layers						,   encoder_attention_heads=self.num_attention_heads						,   decoder_attention_heads=self.num_attention_heads						,   encoder_ffn_dim=self.intermediate_size						,   decoder_ffn_dim=self.intermediate_size						,   dropout=self.hidden_dropout_prob						,   attention_dropout=self.attention_probs_dropout_prob						,   max_position_embeddings=self.max_position_embeddings						,   eos_token_id=self.eos_token_id						,   bos_token_id=self.bos_token_id						,   pad_token_id=self.pad_token_id						,   initializer_range=self.initializer_range						,   use_cache=lowerCamelCase_						,   )
							_lowerCamelCase  :    Optional[int]					=					prepare_blenderbot_inputs_dict(lowerCamelCase_						,   lowerCamelCase_						,   lowerCamelCase_						)
							return config, inputs_dict
			def       A_					(						self						):
							_lowerCamelCase  :    List[str]					=					self.prepare_config_and_inputs()
							return config, inputs_dict
			def       A_					(						self						,   lowercase						,   lowercase						,   lowercase						):
							_lowerCamelCase  :    List[str]					=					20
							_lowerCamelCase  :    str					=					model_class_name(lowerCamelCase_						)

							_lowerCamelCase  :    int					=					model.encode(inputs_dict['input_ids']						)

							_lowerCamelCase  :    List[str]					=					(
							    inputs_dict["""decoder_input_ids"""],
							    inputs_dict["""decoder_attention_mask"""],
							)

							_lowerCamelCase  :    List[str]					=					model.init_cache(decoder_input_ids.shape[0]						,   lowerCamelCase_						,   lowerCamelCase_						)
							_lowerCamelCase  :    Union[str, Any]					=					jnp.ones((decoder_input_ids.shape[0], max_decoder_length)						,   dtype='i4'						)

							_lowerCamelCase  :    Any					=					jnp.broadcast_to(
							    jnp.arange(decoder_input_ids.shape[-1] - 1						)[None, :]						,   (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1)						,   )
							_lowerCamelCase  :    Tuple					=					model.decode(
							    decoder_input_ids[:, :-1]						,   lowerCamelCase_						,   decoder_attention_mask=lowerCamelCase_						,   past_key_values=lowerCamelCase_						,   decoder_position_ids=lowerCamelCase_						,   )

							_lowerCamelCase  :    Tuple					=					jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]]						,   dtype='i4'						)
							_lowerCamelCase  :    Tuple					=					model.decode(
							    decoder_input_ids[:, -1:]						,   lowerCamelCase_						,   decoder_attention_mask=lowerCamelCase_						,   past_key_values=outputs_cache.past_key_values						,   decoder_position_ids=lowerCamelCase_						,   )

							_lowerCamelCase  :    List[Any]					=					model.decode(lowerCamelCase_						,   lowerCamelCase_						)

							_lowerCamelCase  :    Optional[int]					=					np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])						)						)
							self.parent.assertTrue(diff < 1E-3						,   msg=F'''Max diff is {diff}'''						)






			def       A_					(						self						,   lowercase						,   lowercase						,   lowercase						):
							_lowerCamelCase  :    Any					=					20
							_lowerCamelCase  :    Union[str, Any]					=					model_class_name(lowerCamelCase_						)

							_lowerCamelCase  :    Optional[Any]					=					model.encode(inputs_dict['input_ids']						)

							_lowerCamelCase  :    Tuple					=					(
							    inputs_dict["""decoder_input_ids"""],
							    inputs_dict["""decoder_attention_mask"""],
							)

							_lowerCamelCase  :    Optional[Any]					=					jnp.concatenate(
							    [
							        decoder_attention_mask,
							        jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1])						),
							    ]						,   axis=-1						,   )

							_lowerCamelCase  :    Dict					=					model.init_cache(decoder_input_ids.shape[0]						,   lowerCamelCase_						,   lowerCamelCase_						)
							_lowerCamelCase  :    Any					=					jnp.broadcast_to(
							    jnp.arange(decoder_input_ids.shape[-1] - 1						)[None, :]						,   (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1)						,   )

							_lowerCamelCase  :    str					=					model.decode(
							    decoder_input_ids[:, :-1]						,   lowerCamelCase_						,   decoder_attention_mask=lowerCamelCase_						,   past_key_values=lowerCamelCase_						,   decoder_position_ids=lowerCamelCase_						,   )
							_lowerCamelCase  :    List[str]					=					jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]]						,   dtype='i4'						)
							_lowerCamelCase  :    Any					=					model.decode(
							    decoder_input_ids[:, -1:]						,   lowerCamelCase_						,   past_key_values=outputs_cache.past_key_values						,   decoder_attention_mask=lowerCamelCase_						,   decoder_position_ids=lowerCamelCase_						,   )

							_lowerCamelCase  :    str					=					model.decode(lowerCamelCase_						,   lowerCamelCase_						,   decoder_attention_mask=lowerCamelCase_						)

							_lowerCamelCase  :    Tuple					=					np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])						)						)
							self.parent.assertTrue(diff < 1E-3						,   msg=F'''Max diff is {diff}'''						)






@require_flax
class lowerCAmelCase__			(  unittest.TestCase		):






			'''simple docstring'''



			lowerCamelCase__   =    99
			def       A_					(						self						):
							_lowerCamelCase  :    Optional[Any]					=					np.array(
							    [
							        [71, 82, 18, 33, 46, 91, 2],
							        [68, 34, 26, 58, 30, 82, 2],
							        [5, 97, 17, 39, 94, 40, 2],
							        [76, 83, 94, 25, 70, 78, 2],
							        [87, 59, 41, 35, 48, 66, 2],
							        [55, 13, 16, 58, 5, 2, 1],  # note padding
							        [64, 27, 31, 51, 12, 75, 2],
							        [52, 64, 86, 17, 83, 39, 2],
							        [48, 61, 9, 24, 71, 82, 2],
							        [26, 1, 60, 48, 22, 13, 2],
							        [21, 5, 62, 28, 14, 76, 2],
							        [45, 98, 37, 86, 59, 48, 2],
							        [70, 70, 50, 9, 28, 0, 2],
							    ]						,   dtype=np.intaa						,   )

							_lowerCamelCase  :    Tuple					=					input_ids.shape[0]
							_lowerCamelCase  :    int					=					BlenderbotConfig(
							    vocab_size=self.vocab_size						,   d_model=24						,   encoder_layers=2						,   decoder_layers=2						,   encoder_attention_heads=2						,   decoder_attention_heads=2						,   encoder_ffn_dim=32						,   decoder_ffn_dim=32						,   max_position_embeddings=48						,   eos_token_id=2						,   pad_token_id=1						,   bos_token_id=0						,   )
							return config, input_ids, batch_size
			def       A_					(						self						):
							_lowerCamelCase  :    Dict					=					self._get_config_and_data()
							_lowerCamelCase  :    Any					=					FlaxBlenderbotForConditionalGeneration(lowerCamelCase_						)
							_lowerCamelCase  :    Dict					=					lm_model(input_ids=lowerCamelCase_						)
							_lowerCamelCase  :    int					=					(batch_size, input_ids.shape[1], config.vocab_size)
							self.assertEqual(outputs['logits'].shape						,   lowerCamelCase_						)
			def       A_					(						self						):
							_lowerCamelCase  :    Dict					=					BlenderbotConfig(
							    vocab_size=self.vocab_size						,   d_model=14						,   encoder_layers=2						,   decoder_layers=2						,   encoder_attention_heads=2						,   decoder_attention_heads=2						,   encoder_ffn_dim=8						,   decoder_ffn_dim=8						,   max_position_embeddings=48						,   )
							_lowerCamelCase  :    Tuple					=					FlaxBlenderbotForConditionalGeneration(lowerCamelCase_						)
							_lowerCamelCase  :    Tuple					=					np.array([[71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 2, 1]]						,   dtype=np.intaa						)
							_lowerCamelCase  :    str					=					np.array([[82, 71, 82, 18, 2], [58, 68, 2, 1, 1]]						,   dtype=np.intaa						)
							_lowerCamelCase  :    List[str]					=					lm_model(input_ids=lowerCamelCase_						,   decoder_input_ids=lowerCamelCase_						)
							_lowerCamelCase  :    Optional[int]					=					(*summary.shape, config.vocab_size)
							self.assertEqual(outputs['logits'].shape						,   lowerCamelCase_						)






			def       A_					(						self						):
							_lowerCamelCase  :    Any					=					np.array([[71, 82, 18, 33, 2, 1, 1], [68, 34, 26, 58, 30, 82, 2]]						,   dtype=np.intaa						)
							_lowerCamelCase  :    List[Any]					=					shift_tokens_right(lowerCamelCase_						,   1						,   2						)
							_lowerCamelCase  :    Tuple					=					np.equal(lowerCamelCase_						,   1						).astype(np.floataa						).sum()
							_lowerCamelCase  :    Union[str, Any]					=					np.equal(lowerCamelCase_						,   1						).astype(np.floataa						).sum()
							self.assertEqual(shifted.shape						,   input_ids.shape						)
							self.assertEqual(lowerCamelCase_						,   n_pad_before - 1						)
							self.assertTrue(np.equal(shifted[:, 0]						,   2						).all()						)






@require_flax
class lowerCAmelCase__			(  lowercase_,			unittest.TestCase,			lowercase_		):






			'''simple docstring'''



			lowerCamelCase__   =    True
			lowerCamelCase__   =    (
			    (
			        FlaxBlenderbotModel,
			        FlaxBlenderbotForConditionalGeneration,
			    )
			    if is_flax_available()
			    else ()
			)
			lowerCamelCase__   =    (FlaxBlenderbotForConditionalGeneration,) if is_flax_available() else ()
			def       A_					(						self						):
							_lowerCamelCase  :    int					=					FlaxBlenderbotModelTester(self						)
			def       A_					(						self						):
							_lowerCamelCase  :    Dict					=					self.model_tester.prepare_config_and_inputs()
							for model_class in self.all_model_classes:
											self.model_tester.check_use_cache_forward(lowerCamelCase_						,   lowerCamelCase_						,   lowerCamelCase_						)
			def       A_					(						self						):
							_lowerCamelCase  :    Dict					=					self.model_tester.prepare_config_and_inputs()
							for model_class in self.all_model_classes:
											self.model_tester.check_use_cache_forward_with_attn_mask(lowerCamelCase_						,   lowerCamelCase_						,   lowerCamelCase_						)
			def       A_					(						self						):
							_lowerCamelCase  :    int					=					self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
											with self.subTest(model_class.__name__						):
															_lowerCamelCase  :    Dict					=					self._prepare_for_class(lowerCamelCase_						,   lowerCamelCase_						)
															_lowerCamelCase  :    Optional[Any]					=					model_class(lowerCamelCase_						)

															@jax.jit
															def encode_jitted(lowercase						,   lowercase=None						,   **lowercase						):
																			return model.encode(input_ids=lowerCamelCase_						,   attention_mask=lowerCamelCase_						)

															with self.subTest('JIT Enabled'						):
																			_lowerCamelCase  :    Any					=					encode_jitted(**lowerCamelCase_						).to_tuple()

															with self.subTest('JIT Disabled'						):
																			with jax.disable_jit():
																							_lowerCamelCase  :    Dict					=					encode_jitted(**lowerCamelCase_						).to_tuple()

															self.assertEqual(len(lowerCamelCase_						)						,   len(lowerCamelCase_						)						)
															for jitted_output, output in zip(lowerCamelCase_						,   lowerCamelCase_						):
																			self.assertEqual(jitted_output.shape						,   output.shape						)
			def       A_					(						self						):
							_lowerCamelCase  :    Tuple					=					self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
											with self.subTest(model_class.__name__						):
															_lowerCamelCase  :    Optional[int]					=					model_class(lowerCamelCase_						)
															_lowerCamelCase  :    Dict					=					model.encode(inputs_dict['input_ids']						,   inputs_dict['attention_mask']						)

															_lowerCamelCase  :    List[Any]					=					{
															    """decoder_input_ids""": inputs_dict["""decoder_input_ids"""],
															    """decoder_attention_mask""": inputs_dict["""decoder_attention_mask"""],
															    """encoder_outputs""": encoder_outputs,
															}

															@jax.jit
															def decode_jitted(lowercase						,   lowercase						,   lowercase						):
																			return model.decode(
																			    decoder_input_ids=lowerCamelCase_						,   decoder_attention_mask=lowerCamelCase_						,   encoder_outputs=lowerCamelCase_						,   )

															with self.subTest('JIT Enabled'						):
																			_lowerCamelCase  :    List[Any]					=					decode_jitted(**lowerCamelCase_						).to_tuple()

															with self.subTest('JIT Disabled'						):
																			with jax.disable_jit():
																							_lowerCamelCase  :    int					=					decode_jitted(**lowerCamelCase_						).to_tuple()

															self.assertEqual(len(lowerCamelCase_						)						,   len(lowerCamelCase_						)						)
															for jitted_output, output in zip(lowerCamelCase_						,   lowerCamelCase_						):
																			self.assertEqual(jitted_output.shape						,   output.shape						)
			@slow
			def       A_					(						self						):



							for model_class_name in self.all_model_classes:
											_lowerCamelCase  :    str					=					model_class_name.from_pretrained('facebook/blenderbot-400M-distill'						)
											# FlaxBlenderbotForSequenceClassification expects eos token in input_ids
											_lowerCamelCase  :    Dict					=					np.ones((1, 1)						) * model.config.eos_token_id
											_lowerCamelCase  :    Optional[Any]					=					model(lowerCamelCase_						)
											self.assertIsNotNone(lowerCamelCase_						)






			@unittest.skipUnless(jax_device != 'cpu'						,   '3B test too slow on CPU.'						)
			@slow
			def       A_					(						self						):
							_lowerCamelCase  :    int					=					{"""num_beams""": 1, """early_stopping""": True, """min_length""": 15, """max_length""": 25}
							_lowerCamelCase  :    Any					=					{"""skip_special_tokens""": True, """clean_up_tokenization_spaces""": True}

							_lowerCamelCase  :    List[str]					=					FlaxBlenderbotForConditionalGeneration.from_pretrained('facebook/blenderbot-3B'						,   from_pt=lowerCamelCase_						)
							_lowerCamelCase  :    List[Any]					=					BlenderbotTokenizer.from_pretrained('facebook/blenderbot-3B'						)

							_lowerCamelCase  :    str					=					["""Sam"""]
							_lowerCamelCase  :    str					=					tokenizer(lowerCamelCase_						,   return_tensors='jax'						)

							_lowerCamelCase  :    Union[str, Any]					=					model.generate(**lowerCamelCase_						,   **lowerCamelCase_						)
							_lowerCamelCase  :    int					=					"""Sam is a great name. It means \"sun\" in Gaelic."""

							_lowerCamelCase  :    int					=					tokenizer.batch_decode(lowerCamelCase_						,   **lowerCamelCase_						)
							assert generated_txt[0].strip() == tgt_text





"""simple docstring"""






from copy import deepcopy
from typing import Optional, Union

import numpy as np

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
from ...utils import TensorType, is_tf_available, is_torch_available


if is_torch_available():
			import torch

if is_tf_available():
			import tensorflow as tf






class lowerCAmelCase__			(  lowercase		):






			'''simple docstring'''



			lowerCamelCase__   =    ["""image_processor"""]
			lowerCamelCase__   =    """SamImageProcessor"""
			def __init__(						self						,   lowercase						):
							super().__init__(lowercase						)
							_lowerCamelCase  :    str					=					self.image_processor
							_lowerCamelCase  :    Optional[int]					=					-10
							_lowerCamelCase  :    Optional[Any]					=					self.image_processor.size['longest_edge']
			def __call__(						self						,   lowercase=None						,   lowercase=None						,   lowercase=None						,   lowercase=None						,   lowercase = None						,   **lowercase						,   ):
							_lowerCamelCase  :    int					=					self.image_processor(
							    lowercase						,   return_tensors=lowercase						,   **lowercase						,   )

							# pop arguments that are not used in the foward but used nevertheless
							_lowerCamelCase  :    int					=					encoding_image_processor['original_sizes']

							if hasattr(lowercase						,   'numpy'						):  # Checks if Torch or TF tensor
											_lowerCamelCase  :    Tuple					=					original_sizes.numpy()

							_lowerCamelCase,				_lowerCamelCase,				_lowerCamelCase  :    Optional[Any]					=					self._check_and_preprocess_points(
							    input_points=lowercase						,   input_labels=lowercase						,   input_boxes=lowercase						,   )

							_lowerCamelCase  :    Tuple					=					self._normalize_and_convert(
							    lowercase						,   lowercase						,   input_points=lowercase						,   input_labels=lowercase						,   input_boxes=lowercase						,   return_tensors=lowercase						,   )

							return encoding_image_processor
			def       A_					(						self						,   lowercase						,   lowercase						,   lowercase=None						,   lowercase=None						,   lowercase=None						,   lowercase="pt"						,   ):
							if input_points is not None:
											if len(lowercase						) != len(lowercase						):
															_lowerCamelCase  :    str					=					[
															    self._normalize_coordinates(self.target_size						,   lowercase						,   original_sizes[0]						) for point in input_points
															]
											else:
															_lowerCamelCase  :    Optional[Any]					=					[
															    self._normalize_coordinates(self.target_size						,   lowercase						,   lowercase						)
															    for point, original_size in zip(lowercase						,   lowercase						)
															]
											# check that all arrays have the same shape
											if not all(point.shape == input_points[0].shape for point in input_points						):
															if input_labels is not None:
																			_lowerCamelCase,				_lowerCamelCase  :    List[str]					=					self._pad_points_and_labels(lowercase						,   lowercase						)

											_lowerCamelCase  :    Optional[int]					=					np.array(lowercase						)

							if input_labels is not None:
											_lowerCamelCase  :    List[Any]					=					np.array(lowercase						)

							if input_boxes is not None:
											if len(lowercase						) != len(lowercase						):
															_lowerCamelCase  :    Optional[int]					=					[
															    self._normalize_coordinates(self.target_size						,   lowercase						,   original_sizes[0]						,   is_bounding_box=lowercase						)
															    for box in input_boxes
															]
											else:
															_lowerCamelCase  :    Optional[int]					=					[
															    self._normalize_coordinates(self.target_size						,   lowercase						,   lowercase						,   is_bounding_box=lowercase						)
															    for box, original_size in zip(lowercase						,   lowercase						)
															]
											_lowerCamelCase  :    Any					=					np.array(lowercase						)

							if input_boxes is not None:
											if return_tensors == "pt":
															_lowerCamelCase  :    List[str]					=					torch.from_numpy(lowercase						)
															# boxes batch size of 1 by default
															_lowerCamelCase  :    str					=					input_boxes.unsqueeze(1						) if len(input_boxes.shape						) != 3 else input_boxes
											elif return_tensors == "tf":
															_lowerCamelCase  :    int					=					tf.convert_to_tensor(lowercase						)
															# boxes batch size of 1 by default
															_lowerCamelCase  :    Union[str, Any]					=					tf.expand_dims(lowercase						,   1						) if len(input_boxes.shape						) != 3 else input_boxes
											encoding_image_processor.update({'input_boxes': input_boxes}						)
							if input_points is not None:
											if return_tensors == "pt":
															_lowerCamelCase  :    Optional[Any]					=					torch.from_numpy(lowercase						)
															# point batch size of 1 by default
															_lowerCamelCase  :    Union[str, Any]					=					input_points.unsqueeze(1						) if len(input_points.shape						) != 4 else input_points
											elif return_tensors == "tf":
															_lowerCamelCase  :    List[str]					=					tf.convert_to_tensor(lowercase						)
															# point batch size of 1 by default
															_lowerCamelCase  :    Union[str, Any]					=					tf.expand_dims(lowercase						,   1						) if len(input_points.shape						) != 4 else input_points
											encoding_image_processor.update({'input_points': input_points}						)
							if input_labels is not None:
											if return_tensors == "pt":
															_lowerCamelCase  :    Union[str, Any]					=					torch.from_numpy(lowercase						)
															# point batch size of 1 by default
															_lowerCamelCase  :    Optional[Any]					=					input_labels.unsqueeze(1						) if len(input_labels.shape						) != 3 else input_labels
											elif return_tensors == "tf":
															_lowerCamelCase  :    Dict					=					tf.convert_to_tensor(lowercase						)
															# point batch size of 1 by default
															_lowerCamelCase  :    Any					=					tf.expand_dims(lowercase						,   1						) if len(input_labels.shape						) != 3 else input_labels
											encoding_image_processor.update({'input_labels': input_labels}						)

							return encoding_image_processor
			def       A_					(						self						,   lowercase						,   lowercase						):
							_lowerCamelCase  :    Optional[int]					=					max([point.shape[0] for point in input_points]						)
							_lowerCamelCase  :    Optional[int]					=					[]
							for i, point in enumerate(lowercase						):
											if point.shape[0] != expected_nb_points:
															_lowerCamelCase  :    Tuple					=					np.concatenate(
															    [point, np.zeros((expected_nb_points - point.shape[0], 2)						) + self.point_pad_value]						,   axis=0						)
															_lowerCamelCase  :    Optional[Any]					=					np.append(input_labels[i]						,   [self.point_pad_value]						)
											processed_input_points.append(lowercase						)
							_lowerCamelCase  :    Any					=					processed_input_points
							return input_points, input_labels
			def       A_					(						self						,   lowercase						,   lowercase						,   lowercase						,   lowercase=False						):
							_lowerCamelCase,				_lowerCamelCase  :    List[str]					=					original_size
							_lowerCamelCase,				_lowerCamelCase  :    Optional[int]					=					self.image_processor._get_preprocess_shape(lowercase						,   longest_edge=lowercase						)
							_lowerCamelCase  :    Tuple					=					deepcopy(lowercase						).astype(lowercase						)

							if is_bounding_box:
											_lowerCamelCase  :    List[str]					=					coords.reshape(-1						,   2						,   2						)

							_lowerCamelCase  :    Optional[Any]					=					coords[..., 0] * (new_w / old_w)
							_lowerCamelCase  :    List[Any]					=					coords[..., 1] * (new_h / old_h)

							if is_bounding_box:
											_lowerCamelCase  :    Union[str, Any]					=					coords.reshape(-1						,   4						)

							return coords
			def       A_					(						self						,   lowercase=None						,   lowercase=None						,   lowercase=None						,   ):
							if input_points is not None:
											if hasattr(lowercase						,   'numpy'						):  # Checks for TF or Torch tensor
															_lowerCamelCase  :    int					=					input_points.numpy().tolist()

											if not isinstance(lowercase						,   lowercase						) or not isinstance(input_points[0]						,   lowercase						):
															raise ValueError('Input points must be a list of list of floating points.'						)
											_lowerCamelCase  :    Optional[int]					=					[np.array(lowercase						) for input_point in input_points]
							else:
											_lowerCamelCase  :    Optional[Any]					=					None

							if input_labels is not None:
											if hasattr(lowercase						,   'numpy'						):
															_lowerCamelCase  :    Any					=					input_labels.numpy().tolist()

											if not isinstance(lowercase						,   lowercase						) or not isinstance(input_labels[0]						,   lowercase						):
															raise ValueError('Input labels must be a list of list integers.'						)
											_lowerCamelCase  :    List[str]					=					[np.array(lowercase						) for label in input_labels]
							else:
											_lowerCamelCase  :    List[str]					=					None

							if input_boxes is not None:
											if hasattr(lowercase						,   'numpy'						):
															_lowerCamelCase  :    Optional[int]					=					input_boxes.numpy().tolist()

											if (
											    not isinstance(lowercase						,   lowercase						)
											    or not isinstance(input_boxes[0]						,   lowercase						)
											    or not isinstance(input_boxes[0][0]						,   lowercase						)
											):
															raise ValueError('Input boxes must be a list of list of list of floating points.'						)
											_lowerCamelCase  :    int					=					[np.array(lowercase						).astype(np.floataa						) for box in input_boxes]
							else:
											_lowerCamelCase  :    str					=					None

							return input_points, input_labels, input_boxes
			@property
			def       A_					(						self						):
							_lowerCamelCase  :    Optional[Any]					=					self.image_processor.model_input_names
							return list(dict.fromkeys(lowercase						)						)






			def       A_					(						self						,   *lowercase						,   **lowercase						):
							return self.image_processor.post_process_masks(*lowercase						,   **lowercase						)