


import json
import pathlib
import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision, slow
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
				import torch

if is_vision_available():
				from PIL import Image

				from transformers import DetaImageProcessor






class       _UpperCamelCase    (					unittest.TestCase				):

				"""simple docstring"""







				def __init__(						self				,   a__				,   a__=7				,   a__=3				,   a__=30				,   a__=400				,   a__=True				,   a__=None				,   a__=True				,   a__=[0.5, 0.5, 0.5]				,   a__=[0.5, 0.5, 0.5]				,   a__=True				,   a__=1 / 255				,   a__=True				,   )	->				Tuple:
					# by setting size["longest_edge"] > max_resolution we're effectively not testing this :p
					A								=				size if size is not None else {"""shortest_edge""": 18, """longest_edge""": 1333}
					A								=				parent
					A								=				batch_size
					A								=				num_channels
					A								=				min_resolution
					A								=				max_resolution
					A								=				do_resize
					A								=				size
					A								=				do_normalize
					A								=				image_mean
					A								=				image_std
					A								=				do_rescale
					A								=				rescale_factor
					A								=				do_pad

				def      _UpperCAmelCase					(						self   )	->				Any:
					return {
					    "do_resize": self.do_resize,
					    "size": self.size,
					    "do_normalize": self.do_normalize,
					    "image_mean": self.image_mean,
					    "image_std": self.image_std,
					    "do_rescale": self.do_rescale,
					    "rescale_factor": self.rescale_factor,
					    "do_pad": self.do_pad,
					}

				def      _UpperCAmelCase					(						self				,   a__				,   a__=False   )	->				Tuple:
					if not batched:
						A								=				image_inputs[0]
						if isinstance(a__				,   Image.Image   ):
							A					,			A								=				image.size
						else:
							A					,			A								=				image.shape[1], image.shape[2]
						if w < h:
							A								=				int(self.size["""shortest_edge"""] * h / w   )
							A								=				self.size["""shortest_edge"""]
						elif w > h:
							A								=				self.size["""shortest_edge"""]
							A								=				int(self.size["""shortest_edge"""] * w / h   )
						else:
							A								=				self.size["""shortest_edge"""]
							A								=				self.size["""shortest_edge"""]

					else:
						A								=				[]
						for image in image_inputs:
							A					,			A								=				self.get_expected_values([image]   )
							expected_values.append((expected_height, expected_width)   )
						A								=				max(a__				,   key=lambda a__   : item[0]   )[0]
						A								=				max(a__				,   key=lambda a__   : item[1]   )[1]

					return expected_height, expected_width






@require_torch
@require_vision
class       _UpperCamelCase    (					__snake_case    ,		unittest.TestCase				):

				"""simple docstring"""







				lowerCAmelCase 		= DetaImageProcessor if is_vision_available() else None

				def      _UpperCAmelCase					(						self   )	->				Dict:
					A								=				DetaImageProcessingTester(self   )

				@property
				def      _UpperCAmelCase					(						self   )	->				List[Any]:
					return self.image_processor_tester.prepare_image_processor_dict()

				def      _UpperCAmelCase					(						self   )	->				List[Any]:
					A								=				self.image_processing_class(**self.image_processor_dict   )
					self.assertTrue(hasattr(a__				,   """image_mean"""   )   )
					self.assertTrue(hasattr(a__				,   """image_std"""   )   )
					self.assertTrue(hasattr(a__				,   """do_normalize"""   )   )
					self.assertTrue(hasattr(a__				,   """do_resize"""   )   )
					self.assertTrue(hasattr(a__				,   """do_rescale"""   )   )
					self.assertTrue(hasattr(a__				,   """do_pad"""   )   )
					self.assertTrue(hasattr(a__				,   """size"""   )   )

				def      _UpperCAmelCase					(						self   )	->				str:
					A								=				self.image_processing_class.from_dict(self.image_processor_dict   )
					self.assertEqual(image_processor.size				,   {"""shortest_edge""": 18, """longest_edge""": 1333}   )
					self.assertEqual(image_processor.do_pad				,   a__   )

				def      _UpperCAmelCase					(						self   )	->				int:
					pass

				def      _UpperCAmelCase					(						self   )	->				Optional[int]:
					# Initialize image_processing
					A								=				self.image_processing_class(**self.image_processor_dict   )
					# create random PIL images
					A								=				prepare_image_inputs(self.image_processor_tester				,   equal_resolution=a__   )
					for image in image_inputs:
						self.assertIsInstance(a__				,   Image.Image   )

					# Test not batched input
					A								=				image_processing(image_inputs[0]				,   return_tensors="""pt"""   ).pixel_values

					A					,			A								=				self.image_processor_tester.get_expected_values(a__   )

					self.assertEqual(
					    encoded_images.shape				,   (1, self.image_processor_tester.num_channels, expected_height, expected_width)				,   )

					# Test batched
					A					,			A								=				self.image_processor_tester.get_expected_values(a__				,   batched=a__   )

					A								=				image_processing(a__				,   return_tensors="""pt"""   ).pixel_values
					self.assertEqual(
					    encoded_images.shape				,   (
					        self.image_processor_tester.batch_size,
					        self.image_processor_tester.num_channels,
					        expected_height,
					        expected_width,
					    )				,   )

				def      _UpperCAmelCase					(						self   )	->				str:
					# Initialize image_processing
					A								=				self.image_processing_class(**self.image_processor_dict   )
					# create random numpy tensors
					A								=				prepare_image_inputs(self.image_processor_tester				,   equal_resolution=a__				,   numpify=a__   )
					for image in image_inputs:
						self.assertIsInstance(a__				,   np.ndarray   )

					# Test not batched input
					A								=				image_processing(image_inputs[0]				,   return_tensors="""pt"""   ).pixel_values

					A					,			A								=				self.image_processor_tester.get_expected_values(a__   )

					self.assertEqual(
					    encoded_images.shape				,   (1, self.image_processor_tester.num_channels, expected_height, expected_width)				,   )

					# Test batched
					A								=				image_processing(a__				,   return_tensors="""pt"""   ).pixel_values

					A					,			A								=				self.image_processor_tester.get_expected_values(a__				,   batched=a__   )

					self.assertEqual(
					    encoded_images.shape				,   (
					        self.image_processor_tester.batch_size,
					        self.image_processor_tester.num_channels,
					        expected_height,
					        expected_width,
					    )				,   )

				def      _UpperCAmelCase					(						self   )	->				List[str]:
					# Initialize image_processing
					A								=				self.image_processing_class(**self.image_processor_dict   )
					# create random PyTorch tensors
					A								=				prepare_image_inputs(self.image_processor_tester				,   equal_resolution=a__				,   torchify=a__   )
					for image in image_inputs:
						self.assertIsInstance(a__				,   torch.Tensor   )

					# Test not batched input
					A								=				image_processing(image_inputs[0]				,   return_tensors="""pt"""   ).pixel_values

					A					,			A								=				self.image_processor_tester.get_expected_values(a__   )

					self.assertEqual(
					    encoded_images.shape				,   (1, self.image_processor_tester.num_channels, expected_height, expected_width)				,   )

					# Test batched
					A								=				image_processing(a__				,   return_tensors="""pt"""   ).pixel_values

					A					,			A								=				self.image_processor_tester.get_expected_values(a__				,   batched=a__   )

					self.assertEqual(
					    encoded_images.shape				,   (
					        self.image_processor_tester.batch_size,
					        self.image_processor_tester.num_channels,
					        expected_height,
					        expected_width,
					    )				,   )

				@slow
				def      _UpperCAmelCase					(						self   )	->				Optional[Any]:
					# prepare image and target
					A								=				Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""   )
					with open("""./tests/fixtures/tests_samples/COCO/coco_annotations.txt"""				,   """r"""   ) as f:
						A								=				json.loads(f.read()   )

					A								=				{"""image_id""": 3_9769, """annotations""": target}

					# encode them
					A								=				DetaImageProcessor()
					A								=				image_processing(images=a__				,   annotations=a__				,   return_tensors="""pt"""   )

					# verify pixel values
					A								=				torch.Size([1, 3, 800, 1066]   )
					self.assertEqual(encoding["""pixel_values"""].shape				,   a__   )

					A								=				torch.tensor([0.27_96, 0.31_38, 0.34_81]   )
					self.assertTrue(torch.allclose(encoding["""pixel_values"""][0, 0, 0, :3]				,   a__				,   atol=1e-4   )   )

					# verify area
					A								=				torch.tensor([58_87.96_00, 1_12_50.20_61, 48_93_53.84_38, 83_71_22.75_00, 14_79_67.51_56, 16_57_32.34_38]   )
					self.assertTrue(torch.allclose(encoding["""labels"""][0]["""area"""]				,   a__   )   )
					# verify boxes
					A								=				torch.Size([6, 4]   )
					self.assertEqual(encoding["""labels"""][0]["""boxes"""].shape				,   a__   )
					A								=				torch.tensor([0.55_03, 0.27_65, 0.06_04, 0.22_15]   )
					self.assertTrue(torch.allclose(encoding["""labels"""][0]["""boxes"""][0]				,   a__				,   atol=1e-3   )   )
					# verify image_id
					A								=				torch.tensor([3_9769]   )
					self.assertTrue(torch.allclose(encoding["""labels"""][0]["""image_id"""]				,   a__   )   )
					# verify is_crowd
					A								=				torch.tensor([0, 0, 0, 0, 0, 0]   )
					self.assertTrue(torch.allclose(encoding["""labels"""][0]["""iscrowd"""]				,   a__   )   )
					# verify class_labels
					A								=				torch.tensor([75, 75, 63, 65, 17, 17]   )
					self.assertTrue(torch.allclose(encoding["""labels"""][0]["""class_labels"""]				,   a__   )   )
					# verify orig_size
					A								=				torch.tensor([480, 640]   )
					self.assertTrue(torch.allclose(encoding["""labels"""][0]["""orig_size"""]				,   a__   )   )
					# verify size
					A								=				torch.tensor([800, 1066]   )
					self.assertTrue(torch.allclose(encoding["""labels"""][0]["""size"""]				,   a__   )   )

				@slow
				def      _UpperCAmelCase					(						self   )	->				List[Any]:
					# prepare image, target and masks_path
					A								=				Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""   )
					with open("""./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt"""				,   """r"""   ) as f:
						A								=				json.loads(f.read()   )

					A								=				{"""file_name""": """000000039769.png""", """image_id""": 3_9769, """segments_info""": target}

					A								=				pathlib.Path("""./tests/fixtures/tests_samples/COCO/coco_panoptic"""   )

					# encode them
					A								=				DetaImageProcessor(format="""coco_panoptic"""   )
					A								=				image_processing(images=a__				,   annotations=a__				,   masks_path=a__				,   return_tensors="""pt"""   )

					# verify pixel values
					A								=				torch.Size([1, 3, 800, 1066]   )
					self.assertEqual(encoding["""pixel_values"""].shape				,   a__   )

					A								=				torch.tensor([0.27_96, 0.31_38, 0.34_81]   )
					self.assertTrue(torch.allclose(encoding["""pixel_values"""][0, 0, 0, :3]				,   a__				,   atol=1e-4   )   )

					# verify area
					A								=				torch.tensor([14_79_79.68_75, 16_55_27.04_69, 48_46_38.59_38, 1_12_92.93_75, 58_79.65_62, 76_34.11_47]   )
					self.assertTrue(torch.allclose(encoding["""labels"""][0]["""area"""]				,   a__   )   )
					# verify boxes
					A								=				torch.Size([6, 4]   )
					self.assertEqual(encoding["""labels"""][0]["""boxes"""].shape				,   a__   )
					A								=				torch.tensor([0.26_25, 0.54_37, 0.46_88, 0.86_25]   )
					self.assertTrue(torch.allclose(encoding["""labels"""][0]["""boxes"""][0]				,   a__				,   atol=1e-3   )   )
					# verify image_id
					A								=				torch.tensor([3_9769]   )
					self.assertTrue(torch.allclose(encoding["""labels"""][0]["""image_id"""]				,   a__   )   )
					# verify is_crowd
					A								=				torch.tensor([0, 0, 0, 0, 0, 0]   )
					self.assertTrue(torch.allclose(encoding["""labels"""][0]["""iscrowd"""]				,   a__   )   )
					# verify class_labels
					A								=				torch.tensor([17, 17, 63, 75, 75, 93]   )
					self.assertTrue(torch.allclose(encoding["""labels"""][0]["""class_labels"""]				,   a__   )   )
					# verify masks
					A								=				82_2873
					self.assertEqual(encoding["""labels"""][0]["""masks"""].sum().item()				,   a__   )
					# verify orig_size
					A								=				torch.tensor([480, 640]   )
					self.assertTrue(torch.allclose(encoding["""labels"""][0]["""orig_size"""]				,   a__   )   )
					# verify size
					A								=				torch.tensor([800, 1066]   )
					self.assertTrue(torch.allclose(encoding["""labels"""][0]["""size"""]				,   a__   )   )







from typing import List, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


_lowercase       :      Optional[Any]	=	logging.get_logger(__name__)

_lowercase       :      List[str]	=	{
    "huggingface/informer-tourism-monthly": (
        "https://huggingface.co/huggingface/informer-tourism-monthly/resolve/main/config.json"
    ),
    # See all Informer models at https://huggingface.co/models?filter=informer
}






class       _UpperCamelCase    (					__snake_case				):

				"""simple docstring"""







				lowerCAmelCase 		= 'informer'
				lowerCAmelCase 		= {
				    'hidden_size': 'd_model',
				    'num_attention_heads': 'encoder_attention_heads',
				    'num_hidden_layers': 'encoder_layers',
				}

				def __init__(						self				,   a__ = None				,   a__ = None				,   a__ = "student_t"				,   a__ = "nll"				,   a__ = 1				,   a__ = None				,   a__ = "mean"				,   a__ = 0				,   a__ = 0				,   a__ = 0				,   a__ = 0				,   a__ = None				,   a__ = None				,   a__ = 64				,   a__ = 32				,   a__ = 32				,   a__ = 2				,   a__ = 2				,   a__ = 2				,   a__ = 2				,   a__ = True				,   a__ = "gelu"				,   a__ = 0.05				,   a__ = 0.1				,   a__ = 0.1				,   a__ = 0.1				,   a__ = 0.1				,   a__ = 100				,   a__ = 0.02				,   a__=True				,   a__ = "prob"				,   a__ = 5				,   a__ = True				,   **a__				,   )	->				Union[str, Any]:
					# time series specific configuration
					A								=				prediction_length
					A								=				context_length or prediction_length
					A								=				distribution_output
					A								=				loss
					A								=				input_size
					A								=				num_time_features
					A								=				lags_sequence if lags_sequence is not None else [1, 2, 3, 4, 5, 6, 7]
					A								=				scaling
					A								=				num_dynamic_real_features
					A								=				num_static_real_features
					A								=				num_static_categorical_features

					# set cardinality
					if cardinality and num_static_categorical_features > 0:
						if len(a__   ) != num_static_categorical_features:
							raise ValueError(
							    """The cardinality should be a list of the same length as `num_static_categorical_features`"""   )
						A								=				cardinality
					else:
						A								=				[0]

					# set embedding_dimension
					if embedding_dimension and num_static_categorical_features > 0:
						if len(a__   ) != num_static_categorical_features:
							raise ValueError(
							    """The embedding dimension should be a list of the same length as `num_static_categorical_features`"""   )
						A								=				embedding_dimension
					else:
						A								=				[min(50				,   (cat + 1) // 2   ) for cat in self.cardinality]

					A								=				num_parallel_samples

					# Transformer architecture configuration
					A								=				input_size * len(self.lags_sequence   ) + self._number_of_features
					A								=				d_model
					A								=				encoder_attention_heads
					A								=				decoder_attention_heads
					A								=				encoder_ffn_dim
					A								=				decoder_ffn_dim
					A								=				encoder_layers
					A								=				decoder_layers

					A								=				dropout
					A								=				attention_dropout
					A								=				activation_dropout
					A								=				encoder_layerdrop
					A								=				decoder_layerdrop

					A								=				activation_function
					A								=				init_std

					A								=				use_cache

					# Informer
					A								=				attention_type
					A								=				sampling_factor
					A								=				distil

					super().__init__(is_encoder_decoder=a__				,   **a__   )

				@property
				def      _UpperCAmelCase					(						self   )	->				int:
					return (
					    sum(self.embedding_dimension   )
					    + self.num_dynamic_real_features
					    + self.num_time_features
					    + self.num_static_real_features
					    + self.input_size * 2  # the log1p(abs(loc)) and log(scale) features
					)



