



import shutil
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import (
    is_pt_tf_cross_test,
    require_tf,
    require_torch,
    require_torchvision,
    require_vision,
)
from transformers.utils import is_tf_available, is_torch_available, is_vision_available


if is_vision_available():
							from PIL import Image

							from transformers import AutoProcessor, SamImageProcessor, SamProcessor

if is_torch_available():
							import torch

if is_tf_available():
							import tensorflow as tf







@require_vision
@require_torchvision
class       __lowerCAmelCase   (      unittest.TestCase						):



			def    _lowerCamelCase	(						self       :  List[Any])       ->   Dict:



						"""simple docstring"""






						_UpperCAmelCase			=       tempfile.mkdtemp()
						_UpperCAmelCase			=       SamImageProcessor()
						_UpperCAmelCase			=       SamProcessor(A)
						processor.save_pretrained(self.tmpdirname)



			def    _lowerCamelCase	(						self       :  Dict			,		**A       :  Union[str, Any])       ->   str:



						"""simple docstring"""






						return AutoProcessor.from_pretrained(self.tmpdirname			,		**A).image_processor



			def    _lowerCamelCase	(						self       :  Tuple)       ->   List[str]:



						"""simple docstring"""






						shutil.rmtree(self.tmpdirname)



			def    _lowerCamelCase	(						self       :  List[str])       ->   Optional[Any]:



						"""simple docstring"""






						_UpperCAmelCase			=       [np.random.randint(2_55			,		size=(3, 30, 4_00)			,		dtype=np.uinta)]

						_UpperCAmelCase			=       [Image.fromarray(np.moveaxis(A			,		0			,		-1)) for x in image_inputs]

						return image_inputs



			def    _lowerCamelCase	(						self       :  Union[str, Any])       ->   int:



						"""simple docstring"""






						_UpperCAmelCase			=       SamProcessor(image_processor=self.get_image_processor())
						processor.save_pretrained(self.tmpdirname)

						_UpperCAmelCase			=       self.get_image_processor(do_normalize=A			,		padding_value=1.0)

						_UpperCAmelCase			=       SamProcessor.from_pretrained(self.tmpdirname			,		do_normalize=A			,		padding_value=1.0)

						self.assertEqual(processor.image_processor.to_json_string()			,		image_processor_add_kwargs.to_json_string())
						self.assertIsInstance(processor.image_processor			,		A)



			def    _lowerCamelCase	(						self       :  Optional[int])       ->   Any:



						"""simple docstring"""






						_UpperCAmelCase			=       self.get_image_processor()

						_UpperCAmelCase			=       SamProcessor(image_processor=A)

						_UpperCAmelCase			=       self.prepare_image_inputs()

						_UpperCAmelCase			=       image_processor(A			,		return_tensors='np')
						_UpperCAmelCase			=       processor(images=A			,		return_tensors='np')

						input_feat_extract.pop('original_sizes')  # pop original_sizes as it is popped in the processor
						input_feat_extract.pop('reshaped_input_sizes')  # pop original_sizes as it is popped in the processor

						for key in input_feat_extract.keys():
									self.assertAlmostEqual(input_feat_extract[key].sum()			,		input_processor[key].sum()			,		delta=1E-2)



			@require_torch
			def    _lowerCamelCase	(						self       :  Any)       ->   Tuple:



						"""simple docstring"""






						_UpperCAmelCase			=       self.get_image_processor()

						_UpperCAmelCase			=       SamProcessor(image_processor=A)
						_UpperCAmelCase			=       [torch.ones((1, 3, 5, 5))]

						_UpperCAmelCase			=       [[17_64, 26_46]]

						_UpperCAmelCase			=       [[6_83, 10_24]]
						_UpperCAmelCase			=       processor.post_process_masks(A			,		A			,		A)
						self.assertEqual(masks[0].shape			,		(1, 3, 17_64, 26_46))

						_UpperCAmelCase			=       processor.post_process_masks(
						    A			,		torch.tensor(A)			,		torch.tensor(A))
						self.assertEqual(masks[0].shape			,		(1, 3, 17_64, 26_46))

						# should also work with np
						_UpperCAmelCase			=       [np.ones((1, 3, 5, 5))]
						_UpperCAmelCase			=       processor.post_process_masks(A			,		np.array(A)			,		np.array(A))

						self.assertEqual(masks[0].shape			,		(1, 3, 17_64, 26_46))

						_UpperCAmelCase			=       [[1, 0], [0, 1]]
						with self.assertRaises(A):
									_UpperCAmelCase			=       processor.post_process_masks(A			,		np.array(A)			,		np.array(A))







@require_vision
@require_tf
class       __lowerCAmelCase   (      unittest.TestCase						):



			def    _lowerCamelCase	(						self       :  Any)       ->   Union[str, Any]:



						"""simple docstring"""






						_UpperCAmelCase			=       tempfile.mkdtemp()
						_UpperCAmelCase			=       SamImageProcessor()
						_UpperCAmelCase			=       SamProcessor(A)
						processor.save_pretrained(self.tmpdirname)



			def    _lowerCamelCase	(						self       :  List[str]			,		**A       :  Union[str, Any])       ->   List[str]:



						"""simple docstring"""






						return AutoProcessor.from_pretrained(self.tmpdirname			,		**A).image_processor



			def    _lowerCamelCase	(						self       :  Union[str, Any])       ->   Optional[int]:



						"""simple docstring"""






						shutil.rmtree(self.tmpdirname)



			def    _lowerCamelCase	(						self       :  Union[str, Any])       ->   Optional[Any]:



						"""simple docstring"""






						_UpperCAmelCase			=       [np.random.randint(2_55			,		size=(3, 30, 4_00)			,		dtype=np.uinta)]

						_UpperCAmelCase			=       [Image.fromarray(np.moveaxis(A			,		0			,		-1)) for x in image_inputs]

						return image_inputs



			def    _lowerCamelCase	(						self       :  Optional[int])       ->   List[str]:



						"""simple docstring"""






						_UpperCAmelCase			=       SamProcessor(image_processor=self.get_image_processor())
						processor.save_pretrained(self.tmpdirname)

						_UpperCAmelCase			=       self.get_image_processor(do_normalize=A			,		padding_value=1.0)

						_UpperCAmelCase			=       SamProcessor.from_pretrained(self.tmpdirname			,		do_normalize=A			,		padding_value=1.0)

						self.assertEqual(processor.image_processor.to_json_string()			,		image_processor_add_kwargs.to_json_string())
						self.assertIsInstance(processor.image_processor			,		A)



			def    _lowerCamelCase	(						self       :  List[Any])       ->   Tuple:



						"""simple docstring"""






						_UpperCAmelCase			=       self.get_image_processor()

						_UpperCAmelCase			=       SamProcessor(image_processor=A)

						_UpperCAmelCase			=       self.prepare_image_inputs()

						_UpperCAmelCase			=       image_processor(A			,		return_tensors='np')
						_UpperCAmelCase			=       processor(images=A			,		return_tensors='np')

						input_feat_extract.pop('original_sizes')  # pop original_sizes as it is popped in the processor
						input_feat_extract.pop('reshaped_input_sizes')  # pop reshaped_input_sizes as it is popped in the processor

						for key in input_feat_extract.keys():
									self.assertAlmostEqual(input_feat_extract[key].sum()			,		input_processor[key].sum()			,		delta=1E-2)



			@require_tf
			def    _lowerCamelCase	(						self       :  str)       ->   List[Any]:



						"""simple docstring"""






						_UpperCAmelCase			=       self.get_image_processor()

						_UpperCAmelCase			=       SamProcessor(image_processor=A)
						_UpperCAmelCase			=       [tf.ones((1, 3, 5, 5))]

						_UpperCAmelCase			=       [[17_64, 26_46]]

						_UpperCAmelCase			=       [[6_83, 10_24]]
						_UpperCAmelCase			=       processor.post_process_masks(A			,		A			,		A			,		return_tensors='tf')
						self.assertEqual(masks[0].shape			,		(1, 3, 17_64, 26_46))

						_UpperCAmelCase			=       processor.post_process_masks(
						    A			,		tf.convert_to_tensor(A)			,		tf.convert_to_tensor(A)			,		return_tensors='tf'			,		)
						self.assertEqual(masks[0].shape			,		(1, 3, 17_64, 26_46))

						# should also work with np
						_UpperCAmelCase			=       [np.ones((1, 3, 5, 5))]
						_UpperCAmelCase			=       processor.post_process_masks(
						    A			,		np.array(A)			,		np.array(A)			,		return_tensors='tf')

						self.assertEqual(masks[0].shape			,		(1, 3, 17_64, 26_46))

						_UpperCAmelCase			=       [[1, 0], [0, 1]]
						with self.assertRaises(tf.errors.InvalidArgumentError):
									_UpperCAmelCase			=       processor.post_process_masks(
									    A			,		np.array(A)			,		np.array(A)			,		return_tensors='tf')







@require_vision
@require_torchvision
class       __lowerCAmelCase   (      unittest.TestCase						):



			def    _lowerCamelCase	(						self       :  Optional[int])       ->   Optional[Any]:



						"""simple docstring"""






						_UpperCAmelCase			=       tempfile.mkdtemp()
						_UpperCAmelCase			=       SamImageProcessor()
						_UpperCAmelCase			=       SamProcessor(A)
						processor.save_pretrained(self.tmpdirname)



			def    _lowerCamelCase	(						self       :  Optional[int]			,		**A       :  List[Any])       ->   Any:



						"""simple docstring"""






						return AutoProcessor.from_pretrained(self.tmpdirname			,		**A).image_processor



			def    _lowerCamelCase	(						self       :  Optional[Any])       ->   Any:



						"""simple docstring"""






						shutil.rmtree(self.tmpdirname)



			def    _lowerCamelCase	(						self       :  Optional[Any])       ->   Optional[Any]:



						"""simple docstring"""






						_UpperCAmelCase			=       [np.random.randint(2_55			,		size=(3, 30, 4_00)			,		dtype=np.uinta)]

						_UpperCAmelCase			=       [Image.fromarray(np.moveaxis(A			,		0			,		-1)) for x in image_inputs]

						return image_inputs



			@is_pt_tf_cross_test
			def    _lowerCamelCase	(						self       :  int)       ->   int:



						"""simple docstring"""






						_UpperCAmelCase			=       self.get_image_processor()

						_UpperCAmelCase			=       SamProcessor(image_processor=A)
						_UpperCAmelCase			=       np.random.randint(0			,		2			,		size=(1, 3, 5, 5)).astype(np.floataa)
						_UpperCAmelCase			=       [tf.convert_to_tensor(A)]
						_UpperCAmelCase			=       [torch.tensor(A)]

						_UpperCAmelCase			=       [[17_64, 26_46]]

						_UpperCAmelCase			=       [[6_83, 10_24]]
						_UpperCAmelCase			=       processor.post_process_masks(
						    A			,		A			,		A			,		return_tensors='tf')
						_UpperCAmelCase			=       processor.post_process_masks(
						    A			,		A			,		A			,		return_tensors='pt')

						self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy()))



			@is_pt_tf_cross_test
			def    _lowerCamelCase	(						self       :  Any)       ->   Any:



						"""simple docstring"""






						_UpperCAmelCase			=       self.get_image_processor()

						_UpperCAmelCase			=       SamProcessor(image_processor=A)

						_UpperCAmelCase			=       self.prepare_image_inputs()

						_UpperCAmelCase			=       image_processor(A			,		return_tensors='pt')['pixel_values'].numpy()
						_UpperCAmelCase			=       processor(images=A			,		return_tensors='pt')['pixel_values'].numpy()

						_UpperCAmelCase			=       image_processor(A			,		return_tensors='tf')['pixel_values'].numpy()
						_UpperCAmelCase			=       processor(images=A			,		return_tensors='tf')['pixel_values'].numpy()

						self.assertTrue(np.allclose(A			,		A))
						self.assertTrue(np.allclose(A			,		A))
						self.assertTrue(np.allclose(A			,		A))






from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_torch_available,
)


UpperCAmelCase__       =	{
    "configuration_mega": ["MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP", "MegaConfig", "MegaOnnxConfig"],
}

try:
							if not is_torch_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							UpperCAmelCase__       =	[
							    "MEGA_PRETRAINED_MODEL_ARCHIVE_LIST",
							    "MegaForCausalLM",
							    "MegaForMaskedLM",
							    "MegaForMultipleChoice",
							    "MegaForQuestionAnswering",
							    "MegaForSequenceClassification",
							    "MegaForTokenClassification",
							    "MegaModel",
							    "MegaPreTrainedModel",
							]

if TYPE_CHECKING:
							from .configuration_mega import MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP, MegaConfig, MegaOnnxConfig

							try:
														if not is_torch_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .modeling_mega import (
														    MEGA_PRETRAINED_MODEL_ARCHIVE_LIST,
														    MegaForCausalLM,
														    MegaForMaskedLM,
														    MegaForMultipleChoice,
														    MegaForQuestionAnswering,
														    MegaForSequenceClassification,
														    MegaForTokenClassification,
														    MegaModel,
														    MegaPreTrainedModel,
														)

else:
							import sys

							UpperCAmelCase__       =	_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
