

import inspect
import unittest

import numpy as np

from tests.test_modeling_common import floats_tensor
from transformers import MaskaFormerConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
	import torch

	from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel

	if is_vision_available():
		from transformers import MaskaFormerImageProcessor

if is_vision_available():
	from PIL import Image



class    _a						:


					'''simple docstring'''






					def __init__(			self   ,	A__   ,	A__=2   ,	A__=True   ,	A__=False   ,	A__=10   ,	A__=3   ,	A__=32 * 8   ,	A__=32 * 8   ,	A__=4   ,	A__=64   ,	):
						A__							:   str					       =		parent
						A__							:   Tuple					       =		batch_size
						A__							:   Any					       =		is_training
						A__							:   Union[str, Any]					       =		use_auxiliary_loss
						A__							:   Optional[int]					       =		num_queries
						A__							:   Optional[Any]					       =		num_channels
						A__							:   Union[str, Any]					       =		min_size
						A__							:   List[str]					       =		max_size
						A__							:   str					       =		num_labels
						A__							:   Optional[Any]					       =		hidden_dim
						A__							:   Dict					       =		hidden_dim






					def   __A      (			self      ):
						A__							:   List[str]					       =		floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]      ).to(
						    A__      )

						A__							:   Tuple					       =		torch.ones([self.batch_size, self.min_size, self.max_size]   ,	device=A__      )

						A__							:   Any					       =		(
						    torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size]   ,	device=A__      ) > 0.5
						).float()
						A__							:   Tuple					       =		(torch.rand((self.batch_size, self.num_labels)   ,	device=A__      ) > 0.5).long()

						A__							:   Optional[Any]					       =		self.get_config()
						return config, pixel_values, pixel_mask, mask_labels, class_labels






					def   __A      (			self      ):
						A__							:   List[str]					       =		MaskaFormerConfig(
						    hidden_size=self.hidden_dim   ,	)
						A__							:   Any					       =		self.num_queries
						A__							:   List[str]					       =		self.num_labels

						A__							:   Optional[int]					       =		[1, 1, 1, 1]
						A__							:   Optional[Any]					       =		self.num_channels

						A__							:   Optional[Any]					       =		64
						A__							:   int					       =		128
						A__							:   Union[str, Any]					       =		self.hidden_dim
						A__							:   Optional[int]					       =		self.hidden_dim
						A__							:   Any					       =		self.hidden_dim
						return config






					def   __A      (			self      ):
						A__       ,       A__       ,       A__       ,       A__       ,       A__							:   Optional[int]					       =		self.prepare_config_and_inputs()
						A__							:   Dict					       =		{"""pixel_values""": pixel_values, """pixel_mask""": pixel_mask}
						return config, inputs_dict






					def   __A      (			self   ,	A__   ,	A__      ):
						A__							:   List[Any]					       =		output.encoder_hidden_states
						A__							:   List[str]					       =		output.pixel_decoder_hidden_states
						A__							:   Tuple					       =		output.transformer_decoder_hidden_states

						self.parent.assertTrue(len(A__      )   ,	len(config.backbone_config.depths      )      )
						self.parent.assertTrue(len(A__      )   ,	len(config.backbone_config.depths      )      )
						self.parent.assertTrue(len(A__      )   ,	config.decoder_layers      )






					def   __A      (			self   ,	A__   ,	A__   ,	A__   ,	A__=False      ):
						with torch.no_grad():
							A__							:   Tuple					       =		MaskaFormerModel(config=A__      )
							model.to(A__      )
							model.eval()

							A__							:   Union[str, Any]					       =		model(pixel_values=A__   ,	pixel_mask=A__      )
							A__							:   Any					       =		model(A__   ,	output_hidden_states=A__      )

						self.parent.assertEqual(
						    output.transformer_decoder_last_hidden_state.shape   ,	(self.batch_size, self.num_queries, self.hidden_dim)   ,	)
						# let's ensure the other two hidden state exists
						self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None      )
						self.parent.assertTrue(output.encoder_last_hidden_state is not None      )

						if output_hidden_states:
							self.check_output_hidden_state(A__   ,	A__      )






					def   __A      (			self   ,	A__   ,	A__   ,	A__   ,	A__   ,	A__      ):
						A__							:   List[str]					       =		MaskaFormerForUniversalSegmentation(config=A__      )
						model.to(A__      )
						model.eval()

						def comm_check_on_output(A__      ):
							# let's still check that all the required stuff is there
							self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None      )
							self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None      )
							self.parent.assertTrue(result.encoder_last_hidden_state is not None      )
							# okay, now we need to check the logits shape
							# due to the encoder compression, masks have a //4 spatial size
							self.parent.assertEqual(
							    result.masks_queries_logits.shape   ,	(self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4)   ,	)
							# + 1 for null class
							self.parent.assertEqual(
							    result.class_queries_logits.shape   ,	(self.batch_size, self.num_queries, self.num_labels + 1)      )

						with torch.no_grad():
							A__							:   int					       =		model(pixel_values=A__   ,	pixel_mask=A__      )
							A__							:   Union[str, Any]					       =		model(A__      )

							comm_check_on_output(A__      )

							A__							:   int					       =		model(
							    pixel_values=A__   ,	pixel_mask=A__   ,	mask_labels=A__   ,	class_labels=A__      )

						comm_check_on_output(A__      )

						self.parent.assertTrue(result.loss is not None      )
						self.parent.assertEqual(result.loss.shape   ,	torch.Size([1]      )      )



@require_torch
class    _a						(__magic_name__		,       __magic_name__		,       unittest.TestCase    ):


					'''simple docstring'''






					UpperCAmelCase__:       List[str]  							=	(MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else ()
					UpperCAmelCase__:       List[str]  							=	{'''feature-extraction''': MaskaFormerModel} if is_torch_available() else {}

					UpperCAmelCase__:       Dict  							=	False
					UpperCAmelCase__:       Tuple  							=	False
					UpperCAmelCase__:       Optional[Any]  							=	False
					UpperCAmelCase__:       Union[str, Any]  							=	False






					def   __A      (			self      ):
						A__							:   List[str]					       =		MaskaFormerModelTester(self      )
						A__							:   Union[str, Any]					       =		ConfigTester(self   ,	config_class=A__   ,	has_text_modality=A__      )






					def   __A      (			self      ):
						self.config_tester.run_common_tests()






					def   __A      (			self      ):
						A__       ,       A__							:   str					       =		self.model_tester.prepare_config_and_inputs_for_common()
						self.model_tester.create_and_check_maskaformer_model(A__   ,	**A__   ,	output_hidden_states=A__      )






					def   __A      (			self      ):
						A__							:   List[str]					       =		self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*A__      )






					@unittest.skip(reason="""Mask2Former does not use inputs_embeds"""      )
					def   __A      (			self      ):
						pass






					@unittest.skip(reason="""Mask2Former does not have a get_input_embeddings method"""      )
					def   __A      (			self      ):
						pass






					@unittest.skip(reason="""Mask2Former is not a generative model"""      )
					def   __A      (			self      ):
						pass






					@unittest.skip(reason="""Mask2Former does not use token embeddings"""      )
					def   __A      (			self      ):
						pass






					@require_torch_multi_gpu
					@unittest.skip(
					    reason="""Mask2Former has some layers using `add_module` which doesn't work well with `nn.DataParallel`"""      )
					def   __A      (			self      ):
						pass






					@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""      )
					def   __A      (			self      ):
						pass






					def   __A      (			self      ):
						A__       ,       A__							:   List[Any]					       =		self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
							A__							:   Optional[int]					       =		model_class(A__      )
							A__							:   Tuple					       =		inspect.signature(model.forward      )
							# signature.parameters is an OrderedDict => so arg_names order is deterministic
							A__							:   Dict					       =		[*signature.parameters.keys()]

							A__							:   Dict					       =		["""pixel_values"""]
							self.assertListEqual(arg_names[:1]   ,	A__      )






					@slow
					def   __A      (			self      ):
						for model_name in ["facebook/mask2former-swin-small-coco-instance"]:
							A__							:   int					       =		MaskaFormerModel.from_pretrained(A__      )
							self.assertIsNotNone(A__      )






					def   __A      (			self      ):
						A__							:   Dict					       =		(self.model_tester.min_size,) * 2
						A__							:   str					       =		{
						    """pixel_values""": torch.randn((2, 3, *size)   ,	device=A__      ),
						    """mask_labels""": torch.randn((2, 10, *size)   ,	device=A__      ),
						    """class_labels""": torch.zeros(2   ,	10   ,	device=A__      ).long(),
						}
						A__							:   Dict					       =		self.model_tester.get_config()

						A__							:   Tuple					       =		MaskaFormerForUniversalSegmentation(A__      ).to(A__      )
						A__							:   Any					       =		model(**A__      )
						self.assertTrue(outputs.loss is not None      )






					def   __A      (			self      ):
						A__       ,       A__							:   Optional[Any]					       =		self.model_tester.prepare_config_and_inputs_for_common()
						self.model_tester.create_and_check_maskaformer_model(A__   ,	**A__   ,	output_hidden_states=A__      )






					def   __A      (			self      ):
						A__       ,       A__							:   int					       =		self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
							A__							:   Optional[int]					       =		model_class(A__      ).to(A__      )
							A__							:   List[Any]					       =		model(**A__   ,	output_attentions=A__      )
							self.assertTrue(outputs.attentions is not None      )






					def   __A      (			self      ):
						if not self.model_tester.is_training:
							return

						A__							:   List[Any]					       =		self.all_model_classes[1]
						A__       ,       A__       ,       A__       ,       A__       ,       A__							:   Any					       =		self.model_tester.prepare_config_and_inputs()

						A__							:   List[str]					       =		model_class(A__      )
						model.to(A__      )
						model.train()

						A__							:   List[Any]					       =		model(A__   ,	mask_labels=A__   ,	class_labels=A__      ).loss
						loss.backward()






					def   __A      (			self      ):
						A__							:   Tuple					       =		self.all_model_classes[1]
						A__       ,       A__       ,       A__       ,       A__       ,       A__							:   Union[str, Any]					       =		self.model_tester.prepare_config_and_inputs()
						A__							:   str					       =		True
						A__							:   Optional[int]					       =		True

						A__							:   Optional[int]					       =		model_class(A__      ).to(A__      )
						model.train()

						A__							:   int					       =		model(A__   ,	mask_labels=A__   ,	class_labels=A__      )

						A__							:   Any					       =		outputs.encoder_hidden_states[0]
						encoder_hidden_states.retain_grad()

						A__							:   Optional[Any]					       =		outputs.pixel_decoder_hidden_states[0]
						pixel_decoder_hidden_states.retain_grad()

						A__							:   List[Any]					       =		outputs.transformer_decoder_hidden_states[0]
						transformer_decoder_hidden_states.retain_grad()

						A__							:   Union[str, Any]					       =		outputs.attentions[0]
						attentions.retain_grad()

						outputs.loss.backward(retain_graph=A__      )

						self.assertIsNotNone(encoder_hidden_states.grad      )
						self.assertIsNotNone(pixel_decoder_hidden_states.grad      )
						self.assertIsNotNone(transformer_decoder_hidden_states.grad      )
						self.assertIsNotNone(attentions.grad      )



A_	:			Any  	=      1E-4

def 						UpperCamelCase ()					->				int:
	A__							:   Optional[Any]					       =		Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
	return image



@require_vision
@slow
class    _a						(unittest.TestCase    ):


					'''simple docstring'''






					@cached_property
					def   __A      (			self      ):
						return "facebook/mask2former-swin-small-coco-instance"






					@cached_property
					def   __A      (			self      ):
						return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints      ) if is_vision_available() else None






					def   __A      (			self      ):
						A__							:   Tuple					       =		MaskaFormerModel.from_pretrained(self.model_checkpoints      ).to(A__      )
						A__							:   Union[str, Any]					       =		self.default_image_processor
						A__							:   Union[str, Any]					       =		prepare_img()
						A__							:   Any					       =		image_processor(A__   ,	return_tensors="""pt"""      ).to(A__      )
						A__							:   Union[str, Any]					       =		inputs["""pixel_values"""].shape
						# check size is divisible by 32
						self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0      )
						# check size
						self.assertEqual(A__   ,	(1, 3, 384, 384)      )

						with torch.no_grad():
							A__							:   Dict					       =		model(**A__      )

						A__							:   Tuple					       =		torch.tensor(
						    [[-0.2_7_9_0, -1.0_7_1_7, -1.1_6_6_8], [-0.5_1_2_8, -0.3_1_2_8, -0.4_9_8_7], [-0.5_8_3_2, 0.1_9_7_1, -0.0_1_9_7]]      ).to(A__      )
						self.assertTrue(
						    torch.allclose(
						        outputs.encoder_last_hidden_state[0, 0, :3, :3]   ,	A__   ,	atol=A__      )      )

						A__							:   Optional[int]					       =		torch.tensor(
						    [[0.8_9_7_3, 1.1_8_4_7, 1.1_7_7_6], [1.1_9_3_4, 1.5_0_4_0, 1.5_1_2_8], [1.1_1_5_3, 1.4_4_8_6, 1.4_9_5_1]]      ).to(A__      )
						self.assertTrue(
						    torch.allclose(
						        outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3]   ,	A__   ,	atol=A__      )      )

						A__							:   List[str]					       =		torch.tensor(
						    [[2.1_1_5_2, 1.7_0_0_0, -0.8_6_0_3], [1.5_8_0_8, 1.8_0_0_4, -0.9_3_5_3], [1.6_0_4_3, 1.7_4_9_5, -0.5_9_9_9]]      ).to(A__      )
						self.assertTrue(
						    torch.allclose(
						        outputs.transformer_decoder_last_hidden_state[0, :3, :3]   ,	A__   ,	atol=A__      )      )






					def   __A      (			self      ):
						A__							:   str					       =		MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints      ).to(A__      ).eval()
						A__							:   Union[str, Any]					       =		self.default_image_processor
						A__							:   Dict					       =		prepare_img()
						A__							:   List[Any]					       =		image_processor(A__   ,	return_tensors="""pt"""      ).to(A__      )
						A__							:   Dict					       =		inputs["""pixel_values"""].shape
						# check size is divisible by 32
						self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0      )
						# check size
						self.assertEqual(A__   ,	(1, 3, 384, 384)      )

						with torch.no_grad():
							A__							:   Tuple					       =		model(**A__      )
						# masks_queries_logits
						A__							:   Optional[int]					       =		outputs.masks_queries_logits
						self.assertEqual(
						    masks_queries_logits.shape   ,	(1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)      )
						A__							:   Tuple					       =		[
						    [-8.7_8_3_9, -9.0_0_5_6, -8.8_1_2_1],
						    [-7.4_1_0_4, -7.0_3_1_3, -6.5_4_0_1],
						    [-6.6_1_0_5, -6.3_4_2_7, -6.4_6_7_5],
						]
						A__							:   Union[str, Any]					       =		torch.tensor(A__      ).to(A__      )
						self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]   ,	A__   ,	atol=A__      )      )
						# class_queries_logits
						A__							:   Tuple					       =		outputs.class_queries_logits
						self.assertEqual(class_queries_logits.shape   ,	(1, model.config.num_queries, model.config.num_labels + 1)      )
						A__							:   Any					       =		torch.tensor(
						    [
						        [1.8_3_2_4, -8.0_8_3_5, -4.1_9_2_2],
						        [0.8_4_5_0, -9.0_0_5_0, -3.6_0_5_3],
						        [0.3_0_4_5, -7.7_2_9_3, -3.0_2_7_5],
						    ]      ).to(A__      )
						self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]   ,	A__   ,	atol=A__      )      )






					def   __A      (			self      ):
						A__							:   Dict					       =		MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints      ).to(A__      ).eval()
						A__							:   Optional[int]					       =		self.default_image_processor

						A__							:   Union[str, Any]					       =		image_processor(
						    [np.zeros((3, 800, 1333)      ), np.zeros((3, 800, 1333)      )]   ,	segmentation_maps=[np.zeros((384, 384)      ).astype(np.floataa      ), np.zeros((384, 384)      ).astype(np.floataa      )]   ,	return_tensors="""pt"""   ,	)

						A__							:   Any					       =		inputs["""pixel_values"""].to(A__      )
						A__							:   int					       =		[el.to(A__      ) for el in inputs["""mask_labels"""]]
						A__							:   Tuple					       =		[el.to(A__      ) for el in inputs["""class_labels"""]]

						with torch.no_grad():
							A__							:   Optional[Any]					       =		model(**A__      )

						self.assertTrue(outputs.loss is not None      )






import requests

A_	:			List[Any]  	=      'YOUR API KEY'

def 						UpperCamelCase (lowercase_:			str   ,				lowercase_:			str = giphy_api_key )					->				list:
	A__							:   Dict					       =		"""+""".join(query.split() )
	A__							:   Optional[int]					       =		f"""https://api.giphy.com/v1/gifs/search?q={formatted_query}&api_key={api_key}"""
	A__							:   Any					       =		requests.get(lowercase_ ).json()["""data"""]
	return [gif["url"] for gif in gifs]


if __name__ == "__main__":
	print('\n'.join(get_gifs('space ship')))



