






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 DeformableDetrImageProcessor




class 			snake_case__   (							unittest.TestCase):

							'''simple docstring'''



							def __init__(							self			,						a__			,						a__=7			,						a__=3			,						a__=30			,						a__=4_00			,						a__=True			,						a__=None			,						a__=True			,						a__=[0.5, 0.5, 0.5]			,						a__=[0.5, 0.5, 0.5]			,						a__=True			,						a__=1 / 2_55			,						a__=True			,						) ->      Optional[Any]:






												'''simple docstring'''





												__snake_case			:List[str]          =						size if size is not None else {"shortest_edge": 18, "longest_edge": 13_33}
												__snake_case			:Optional[Any]          =						parent
												__snake_case			:str          =						batch_size
												__snake_case			:Union[str, Any]          =						num_channels
												__snake_case			:Optional[Any]          =						min_resolution
												__snake_case			:List[str]          =						max_resolution
												__snake_case			:Tuple          =						do_resize
												__snake_case			:str          =						size
												__snake_case			:str          =						do_normalize
												__snake_case			:Optional[Any]          =						image_mean
												__snake_case			:List[str]          =						image_std
												__snake_case			:List[str]          =						do_rescale
												__snake_case			:Tuple          =						rescale_factor
												__snake_case			:Tuple          =						do_pad



							def 					__lowercase						(							self    ) ->      Optional[int]:






												'''simple docstring'''





												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 					__lowercase						(							self			,						a__			,						a__=False    ) ->      Optional[int]:






												'''simple docstring'''





												if not batched:
																	__snake_case			:List[Any]          =						image_inputs[0]
																	if isinstance(__A			,						Image.Image    ):
																						__snake_case			:str          =						image.size
																	else:
																						__snake_case			:Dict          =						image.shape[1], image.shape[2]
																	if w < h:
																						__snake_case			:Any          =						int(self.size["""shortest_edge"""] * h / w    )
																						__snake_case			:Any          =						self.size["shortest_edge"]
																	elif w > h:
																						__snake_case			:Optional[int]          =						self.size["shortest_edge"]
																						__snake_case			:Any          =						int(self.size["""shortest_edge"""] * w / h    )
																	else:
																						__snake_case			:Tuple          =						self.size["shortest_edge"]
																						__snake_case			:int          =						self.size["shortest_edge"]

												else:
																	__snake_case			:Any          =						[]
																	for image in image_inputs:
																						__snake_case			:Optional[Any]          =						self.get_expected_values([image]    )
																						expected_values.append((expected_height, expected_width)    )
																	__snake_case			:List[Any]          =						max(__A			,						key=lambda a__    : item[0]    )[0]
																	__snake_case			:int          =						max(__A			,						key=lambda a__    : item[1]    )[1]

												return expected_height, expected_width




@require_torch
@require_vision
class 			snake_case__   (							UpperCamelCase_	,    unittest.TestCase):

							'''simple docstring'''
							lowerCamelCase							:				Optional[Any] 				= DeformableDetrImageProcessor if is_vision_available() else None



							def 					__lowercase						(							self    ) ->      List[Any]:






												'''simple docstring'''





												__snake_case			:Optional[Any]          =						DeformableDetrImageProcessingTester(self    )



							@property
							def 					__lowercase						(							self    ) ->      Any:






												'''simple docstring'''





												return self.image_processor_tester.prepare_image_processor_dict()



							def 					__lowercase						(							self    ) ->      Any:






												'''simple docstring'''





												__snake_case			:Any          =						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 					__lowercase						(							self    ) ->      Union[str, Any]:






												'''simple docstring'''





												__snake_case			:Union[str, Any]          =						self.image_processing_class.from_dict(self.image_processor_dict    )
												self.assertEqual(image_processor.size			,						{"""shortest_edge""": 18, """longest_edge""": 13_33}    )
												self.assertEqual(image_processor.do_pad			,						__A    )

												__snake_case			:Tuple          =						self.image_processing_class.from_dict(
												    self.image_processor_dict			,						size=42			,						max_size=84			,						pad_and_return_pixel_mask=__A    )
												self.assertEqual(image_processor.size			,						{"""shortest_edge""": 42, """longest_edge""": 84}    )
												self.assertEqual(image_processor.do_pad			,						__A    )



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






												'''simple docstring'''





												pass



							def 					__lowercase						(							self    ) ->      int:






												'''simple docstring'''





												__snake_case			:Any          =						self.image_processing_class(**self.image_processor_dict    )
												# create random PIL images
												__snake_case			:Optional[Any]          =						prepare_image_inputs(self.image_processor_tester			,						equal_resolution=__A    )
												for image in image_inputs:
																	self.assertIsInstance(__A			,						Image.Image    )

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

												__snake_case			:List[str]          =						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
												__snake_case			:List[Any]          =						self.image_processor_tester.get_expected_values(__A			,						batched=__A    )

												__snake_case			:int          =						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 					__lowercase						(							self    ) ->      Optional[int]:






												'''simple docstring'''





												__snake_case			:Any          =						self.image_processing_class(**self.image_processor_dict    )
												# create random numpy tensors
												__snake_case			:str          =						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
												__snake_case			:Optional[Any]          =						image_processing(image_inputs[0]			,						return_tensors="""pt"""    ).pixel_values

												__snake_case			:int          =						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
												__snake_case			:Tuple          =						image_processing(__A			,						return_tensors="""pt"""    ).pixel_values

												__snake_case			:int          =						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 					__lowercase						(							self    ) ->      Optional[Any]:






												'''simple docstring'''





												__snake_case			:Optional[int]          =						self.image_processing_class(**self.image_processor_dict    )
												# create random PyTorch tensors
												__snake_case			:List[str]          =						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
												__snake_case			:str          =						image_processing(image_inputs[0]			,						return_tensors="""pt"""    ).pixel_values

												__snake_case			:Union[str, Any]          =						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
												__snake_case			:Tuple          =						image_processing(__A			,						return_tensors="""pt"""    ).pixel_values

												__snake_case			:Tuple          =						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 					__lowercase						(							self    ) ->      str:






												'''simple docstring'''





												__snake_case			:Tuple          =						Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""    )
												with open("""./tests/fixtures/tests_samples/COCO/coco_annotations.txt"""			,						"""r"""    ) as f:
																	__snake_case			:Tuple          =						json.loads(f.read()    )

												__snake_case			:Union[str, Any]          =						{"image_id": 3_97_69, "annotations": target}

												# encode them
												__snake_case			:str          =						DeformableDetrImageProcessor()
												__snake_case			:Tuple          =						image_processing(images=__A			,						annotations=__A			,						return_tensors="""pt"""    )

												# verify pixel values
												__snake_case			:Optional[Any]          =						torch.Size([1, 3, 8_00, 10_66]    )
												self.assertEqual(encoding["""pixel_values"""].shape			,						__A    )

												__snake_case			:Union[str, Any]          =						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
												__snake_case			:str          =						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
												__snake_case			:Union[str, Any]          =						torch.Size([6, 4]    )
												self.assertEqual(encoding["""labels"""][0]["""boxes"""].shape			,						__A    )
												__snake_case			:List[Any]          =						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
												__snake_case			:Any          =						torch.tensor([3_97_69]    )
												self.assertTrue(torch.allclose(encoding["""labels"""][0]["""image_id"""]			,						__A    )    )
												# verify is_crowd
												__snake_case			:Tuple          =						torch.tensor([0, 0, 0, 0, 0, 0]    )
												self.assertTrue(torch.allclose(encoding["""labels"""][0]["""iscrowd"""]			,						__A    )    )
												# verify class_labels
												__snake_case			:int          =						torch.tensor([75, 75, 63, 65, 17, 17]    )
												self.assertTrue(torch.allclose(encoding["""labels"""][0]["""class_labels"""]			,						__A    )    )
												# verify orig_size
												__snake_case			:List[str]          =						torch.tensor([4_80, 6_40]    )
												self.assertTrue(torch.allclose(encoding["""labels"""][0]["""orig_size"""]			,						__A    )    )
												# verify size
												__snake_case			:Tuple          =						torch.tensor([8_00, 10_66]    )
												self.assertTrue(torch.allclose(encoding["""labels"""][0]["""size"""]			,						__A    )    )



							@slow
							def 					__lowercase						(							self    ) ->      str:






												'''simple docstring'''





												__snake_case			:Dict          =						Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""    )
												with open("""./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt"""			,						"""r"""    ) as f:
																	__snake_case			:Any          =						json.loads(f.read()    )

												__snake_case			:Dict          =						{"file_name": "000000039769.png", "image_id": 3_97_69, "segments_info": target}

												__snake_case			:int          =						pathlib.Path("""./tests/fixtures/tests_samples/COCO/coco_panoptic"""    )

												# encode them
												__snake_case			:List[str]          =						DeformableDetrImageProcessor(format="""coco_panoptic"""    )
												__snake_case			:List[Any]          =						image_processing(images=__A			,						annotations=__A			,						masks_path=__A			,						return_tensors="""pt"""    )

												# verify pixel values
												__snake_case			:List[Any]          =						torch.Size([1, 3, 8_00, 10_66]    )
												self.assertEqual(encoding["""pixel_values"""].shape			,						__A    )

												__snake_case			:Optional[int]          =						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
												__snake_case			:Tuple          =						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
												__snake_case			:Any          =						torch.Size([6, 4]    )
												self.assertEqual(encoding["""labels"""][0]["""boxes"""].shape			,						__A    )
												__snake_case			:Any          =						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
												__snake_case			:List[str]          =						torch.tensor([3_97_69]    )
												self.assertTrue(torch.allclose(encoding["""labels"""][0]["""image_id"""]			,						__A    )    )
												# verify is_crowd
												__snake_case			:Any          =						torch.tensor([0, 0, 0, 0, 0, 0]    )
												self.assertTrue(torch.allclose(encoding["""labels"""][0]["""iscrowd"""]			,						__A    )    )
												# verify class_labels
												__snake_case			:List[str]          =						torch.tensor([17, 17, 63, 75, 75, 93]    )
												self.assertTrue(torch.allclose(encoding["""labels"""][0]["""class_labels"""]			,						__A    )    )
												# verify masks
												__snake_case			:Union[str, Any]          =						82_28_73
												self.assertEqual(encoding["""labels"""][0]["""masks"""].sum().item()			,						__A    )
												# verify orig_size
												__snake_case			:int          =						torch.tensor([4_80, 6_40]    )
												self.assertTrue(torch.allclose(encoding["""labels"""][0]["""orig_size"""]			,						__A    )    )
												# verify size
												__snake_case			:Union[str, Any]          =						torch.tensor([8_00, 10_66]    )
												self.assertTrue(torch.allclose(encoding["""labels"""][0]["""size"""]			,						__A    )    )










# Copyright 2021 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 packaging import version

from .. import __version__
from .constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD
from .doc import (
    add_code_sample_docstrings,
    add_end_docstrings,
    add_start_docstrings,
    add_start_docstrings_to_model_forward,
    copy_func,
    replace_return_docstrings,
)
from .generic import (
    ContextManagers,
    ExplicitEnum,
    ModelOutput,
    PaddingStrategy,
    TensorType,
    add_model_info_to_auto_map,
    cached_property,
    can_return_loss,
    expand_dims,
    find_labels,
    flatten_dict,
    infer_framework,
    is_jax_tensor,
    is_numpy_array,
    is_tensor,
    is_tf_symbolic_tensor,
    is_tf_tensor,
    is_torch_device,
    is_torch_dtype,
    is_torch_tensor,
    reshape,
    squeeze,
    strtobool,
    tensor_size,
    to_numpy,
    to_py_obj,
    transpose,
    working_or_temp_dir,
)
from .hub import (
    CLOUDFRONT_DISTRIB_PREFIX,
    DISABLE_TELEMETRY,
    HF_MODULES_CACHE,
    HUGGINGFACE_CO_PREFIX,
    HUGGINGFACE_CO_RESOLVE_ENDPOINT,
    PYTORCH_PRETRAINED_BERT_CACHE,
    PYTORCH_TRANSFORMERS_CACHE,
    S3_BUCKET_PREFIX,
    TRANSFORMERS_CACHE,
    TRANSFORMERS_DYNAMIC_MODULE_NAME,
    EntryNotFoundError,
    PushToHubMixin,
    RepositoryNotFoundError,
    RevisionNotFoundError,
    cached_file,
    default_cache_path,
    define_sagemaker_information,
    download_url,
    extract_commit_hash,
    get_cached_models,
    get_file_from_repo,
    get_full_repo_name,
    has_file,
    http_user_agent,
    is_offline_mode,
    is_remote_url,
    move_cache,
    send_example_telemetry,
    try_to_load_from_cache,
)
from .import_utils import (
    ENV_VARS_TRUE_AND_AUTO_VALUES,
    ENV_VARS_TRUE_VALUES,
    TORCH_FX_REQUIRED_VERSION,
    USE_JAX,
    USE_TF,
    USE_TORCH,
    DummyObject,
    OptionalDependencyNotAvailable,
    _LazyModule,
    ccl_version,
    direct_transformers_import,
    get_torch_version,
    is_accelerate_available,
    is_apex_available,
    is_bitsandbytes_available,
    is_bsa_available,
    is_coloredlogs_available,
    is_cython_available,
    is_datasets_available,
    is_decord_available,
    is_detectrona_available,
    is_faiss_available,
    is_flax_available,
    is_ftfy_available,
    is_in_notebook,
    is_ipex_available,
    is_jieba_available,
    is_jumanpp_available,
    is_kenlm_available,
    is_keras_nlp_available,
    is_librosa_available,
    is_natten_available,
    is_ninja_available,
    is_onnx_available,
    is_openai_available,
    is_optimum_available,
    is_pandas_available,
    is_peft_available,
    is_phonemizer_available,
    is_protobuf_available,
    is_psutil_available,
    is_pyanvml_available,
    is_pyctcdecode_available,
    is_pytesseract_available,
    is_pytest_available,
    is_pytorch_quantization_available,
    is_rjieba_available,
    is_sacremoses_available,
    is_safetensors_available,
    is_sagemaker_dp_enabled,
    is_sagemaker_mp_enabled,
    is_scipy_available,
    is_sentencepiece_available,
    is_seqio_available,
    is_sklearn_available,
    is_soundfile_availble,
    is_spacy_available,
    is_speech_available,
    is_sudachi_available,
    is_tensorflow_probability_available,
    is_tensorflow_text_available,
    is_tfaonnx_available,
    is_tf_available,
    is_timm_available,
    is_tokenizers_available,
    is_torch_available,
    is_torch_bfaa_available,
    is_torch_bfaa_cpu_available,
    is_torch_bfaa_gpu_available,
    is_torch_compile_available,
    is_torch_cuda_available,
    is_torch_fx_available,
    is_torch_fx_proxy,
    is_torch_mps_available,
    is_torch_neuroncore_available,
    is_torch_tensorrt_fx_available,
    is_torch_tfaa_available,
    is_torch_tpu_available,
    is_torchaudio_available,
    is_torchdistx_available,
    is_torchdynamo_available,
    is_torchvision_available,
    is_training_run_on_sagemaker,
    is_vision_available,
    requires_backends,
    torch_only_method,
)


lowerCamelCase__							=     """pytorch_model.bin"""
lowerCamelCase__							=     """pytorch_model.bin.index.json"""
lowerCamelCase__							=     """adapter_config.json"""
lowerCamelCase__							=     """adapter_model.bin"""
lowerCamelCase__							=     """adapter_model.safetensors"""
lowerCamelCase__							=     """tf_model.h5"""
lowerCamelCase__							=     """tf_model.h5.index.json"""
lowerCamelCase__							=     """model.ckpt"""
lowerCamelCase__							=     """flax_model.msgpack"""
lowerCamelCase__							=     """flax_model.msgpack.index.json"""
lowerCamelCase__							=     """model.safetensors"""
lowerCamelCase__							=     """model.safetensors.index.json"""
lowerCamelCase__							=     """config.json"""
lowerCamelCase__							=     """preprocessor_config.json"""
lowerCamelCase__							=     FEATURE_EXTRACTOR_NAME
lowerCamelCase__							=     """generation_config.json"""
lowerCamelCase__							=     """modelcard.json"""

lowerCamelCase__							=     """▁"""
lowerCamelCase__							=     SENTENCEPIECE_UNDERLINE  # Kept for backward compatibility

lowerCamelCase__							=     [
    [[0, 1, 0, 1], [1, 0, 0, 1]]
] * 2  # Needs to have 0s and 1s only since XLM uses it for langs too.
lowerCamelCase__							=     [[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]]
lowerCamelCase__							=     [[1, 1, 1, 1, 1], [1, 1, 1, 0, 0], [0, 0, 0, 1, 1]]






def   UpperCamelCase  (       snake_case__     :   Dict  ):




     '''simple docstring'''






     if version.parse(snake_case__  ) < version.parse(snake_case__  ):
          if "dev" in min_version:
               __snake_case			:Tuple          =						(
                   """This example requires a source install from HuggingFace Transformers (see """
                   """`https://huggingface.co/docs/transformers/installation#install-from-source`),"""
               )
          else:
               __snake_case			:List[str]          =						f'''This example requires a minimum version of {min_version},'''
          error_message += f''' but the version found is {__version__}.\n'''
          raise ImportError(
              error_message
              + """Check out https://github.com/huggingface/transformers/tree/main/examples#important-note for the examples corresponding to other """
              """versions of HuggingFace Transformers."""  )


