



import json
import unittest

import numpy as np
from huggingface_hub import hf_hub_download

from transformers.testing_utils import require_torch, require_vision
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 transformers import OneFormerImageProcessor
          from transformers.models.oneformer.image_processing_oneformer import binary_mask_to_rle
          from transformers.models.oneformer.modeling_oneformer import OneFormerForUniversalSegmentationOutput

if is_vision_available():
     from PIL import Image

def     __lowercase(	UpperCAmelCase__   ,   UpperCAmelCase__="shi-labs/oneformer_demo" ):


      """simple docstring"""



      with open(hf_hub_download(UpperCAmelCase__   ,   UpperCAmelCase__   ,   repo_type="dataset" )   ,   "r" ) as f:
            lowerCamelCase     :   Any								=		json.load(UpperCAmelCase__ )
      lowerCamelCase     :   str								=		{}
      lowerCamelCase     :   str								=		[]
      lowerCamelCase     :   Tuple								=		[]
      for key, info in class_info.items():
            lowerCamelCase     :   str								=		info["name"]
            class_names.append(info["name"] )
            if info["isthing"]:
                  thing_ids.append(int(UpperCAmelCase__ ) )
      lowerCamelCase     :   Any								=		thing_ids
      lowerCamelCase     :   int								=		class_names
      return metadata





class    lowerCamelCase__  (						unittest.TestCase):
     """simple docstring"""



     def __init__(self				,			__a				,			__a=7				,			__a=3				,			__a=30				,			__a=4_00				,			__a=None				,			__a=True				,			__a=True				,			__a=[0.5, 0.5, 0.5]				,			__a=[0.5, 0.5, 0.5]				,			__a=10				,			__a=False				,			__a=2_55				,			__a="shi-labs/oneformer_demo"				,			__a="ade20k_panoptic.json"				,			__a=10				,			):






           '''simple docstring'''



           lowerCamelCase     :   Optional[Any]								=		parent
           lowerCamelCase     :   Tuple								=		batch_size
           lowerCamelCase     :   str								=		num_channels
           lowerCamelCase     :   Dict								=		min_resolution
           lowerCamelCase     :   Any								=		max_resolution
           lowerCamelCase     :   List[Any]								=		do_resize
           lowerCamelCase     :   Optional[int]								=		{"shortest_edge": 32, "longest_edge": 13_33} if size is None else size
           lowerCamelCase     :   Any								=		do_normalize
           lowerCamelCase     :   Union[str, Any]								=		image_mean
           lowerCamelCase     :   Optional[int]								=		image_std
           lowerCamelCase     :   str								=		class_info_file
           lowerCamelCase     :   Union[str, Any]								=		prepare_metadata(__a				,			__a    )
           lowerCamelCase     :   Union[str, Any]								=		num_text
           lowerCamelCase     :   List[Any]								=		repo_path

           # for the post_process_functions
           lowerCamelCase     :   int								=		2
           lowerCamelCase     :   Optional[int]								=		10
           lowerCamelCase     :   Tuple								=		10
           lowerCamelCase     :   Any								=		3
           lowerCamelCase     :   Any								=		4
           lowerCamelCase     :   Optional[Any]								=		num_labels
           lowerCamelCase     :   Dict								=		do_reduce_labels
           lowerCamelCase     :   Union[str, Any]								=		ignore_index







     def 						_a      (self    ):






           '''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,
               "num_labels": self.num_labels,
               "do_reduce_labels": self.do_reduce_labels,
               "ignore_index": self.ignore_index,
               "class_info_file": self.class_info_file,
               "metadata": self.metadata,
               "num_text": self.num_text,
           }







     def 						_a      (self				,			__a				,			__a=False    ):






           '''simple docstring'''



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

           else:
                 lowerCamelCase     :   List[Any]								=		[]
                 for image in image_inputs:
                       lowerCamelCase			,							lowerCamelCase     :   Tuple								=		self.get_expected_values([image]    )
                       expected_values.append((expected_height, expected_width)    )
                 lowerCamelCase     :   Any								=		max(__a				,			key=lambda __a    : item[0]    )[0]
                 lowerCamelCase     :   List[Any]								=		max(__a				,			key=lambda __a    : item[1]    )[1]

           return expected_height, expected_width







     def 						_a      (self    ):






           '''simple docstring'''



           return OneFormerForUniversalSegmentationOutput(
               # +1 for null class
               class_queries_logits=torch.randn((self.batch_size, self.num_queries, self.num_classes + 1)    )				,			masks_queries_logits=torch.randn((self.batch_size, self.num_queries, self.height, self.width)    )				,			)





@require_torch
@require_vision
class    lowerCamelCase__  (						UpperCAmelCase_       ,    unittest.TestCase):
     """simple docstring"""



     _A       =			OneFormerImageProcessor if (is_vision_available() and is_torch_available()) else None
     # only for test_image_processing_common.test_image_proc_to_json_string
     _A       =			image_processing_class







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase     :   List[Any]								=		OneFormerImageProcessorTester(self    )







     @property
     def 						_a      (self    ):






           '''simple docstring'''



           return self.image_processing_tester.prepare_image_processor_dict()







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase     :   Tuple								=		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				,			"size"    )    )
           self.assertTrue(hasattr(__a				,			"ignore_index"    )    )
           self.assertTrue(hasattr(__a				,			"class_info_file"    )    )
           self.assertTrue(hasattr(__a				,			"num_text"    )    )
           self.assertTrue(hasattr(__a				,			"repo_path"    )    )
           self.assertTrue(hasattr(__a				,			"metadata"    )    )
           self.assertTrue(hasattr(__a				,			"do_reduce_labels"    )    )







     def 						_a      (self    ):






           '''simple docstring'''



           pass







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase     :   int								=		self.image_processing_class(**self.image_processor_dict    )
           # create random PIL images
           lowerCamelCase     :   str								=		prepare_image_inputs(self.image_processing_tester				,			equal_resolution=__a    )
           for image in image_inputs:
                 self.assertIsInstance(__a				,			Image.Image    )

           # Test not batched input
           lowerCamelCase     :   List[str]								=		image_processor(image_inputs[0]				,			["semantic"]				,			return_tensors="pt"    ).pixel_values

           lowerCamelCase			,							lowerCamelCase     :   Optional[int]								=		self.image_processing_tester.get_expected_values(__a    )

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

           # Test batched
           lowerCamelCase			,							lowerCamelCase     :   Dict								=		self.image_processing_tester.get_expected_values(__a				,			batched=__a    )

           lowerCamelCase     :   List[str]								=		image_processor(
               __a				,			["semantic"] * len(__a    )				,			return_tensors="pt"    ).pixel_values
           self.assertEqual(
               encoded_images.shape				,			(
                   self.image_processing_tester.batch_size,
                   self.image_processing_tester.num_channels,
                   expected_height,
                   expected_width,
               )				,			)







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase     :   Tuple								=		self.image_processing_class(**self.image_processor_dict    )
           # create random numpy tensors
           lowerCamelCase     :   Optional[int]								=		prepare_image_inputs(self.image_processing_tester				,			equal_resolution=__a				,			numpify=__a    )
           for image in image_inputs:
                 self.assertIsInstance(__a				,			np.ndarray    )

           # Test not batched input
           lowerCamelCase     :   List[Any]								=		image_processor(image_inputs[0]				,			["semantic"]				,			return_tensors="pt"    ).pixel_values

           lowerCamelCase			,							lowerCamelCase     :   List[str]								=		self.image_processing_tester.get_expected_values(__a    )

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

           # Test batched
           lowerCamelCase			,							lowerCamelCase     :   str								=		self.image_processing_tester.get_expected_values(__a				,			batched=__a    )

           lowerCamelCase     :   Any								=		image_processor(
               __a				,			["semantic"] * len(__a    )				,			return_tensors="pt"    ).pixel_values
           self.assertEqual(
               encoded_images.shape				,			(
                   self.image_processing_tester.batch_size,
                   self.image_processing_tester.num_channels,
                   expected_height,
                   expected_width,
               )				,			)







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase     :   str								=		self.image_processing_class(**self.image_processor_dict    )
           # create random PyTorch tensors
           lowerCamelCase     :   Any								=		prepare_image_inputs(self.image_processing_tester				,			equal_resolution=__a				,			torchify=__a    )
           for image in image_inputs:
                 self.assertIsInstance(__a				,			torch.Tensor    )

           # Test not batched input
           lowerCamelCase     :   Union[str, Any]								=		image_processor(image_inputs[0]				,			["semantic"]				,			return_tensors="pt"    ).pixel_values

           lowerCamelCase			,							lowerCamelCase     :   Union[str, Any]								=		self.image_processing_tester.get_expected_values(__a    )

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

           # Test batched
           lowerCamelCase			,							lowerCamelCase     :   Tuple								=		self.image_processing_tester.get_expected_values(__a				,			batched=__a    )

           lowerCamelCase     :   str								=		image_processor(
               __a				,			["semantic"] * len(__a    )				,			return_tensors="pt"    ).pixel_values
           self.assertEqual(
               encoded_images.shape				,			(
                   self.image_processing_tester.batch_size,
                   self.image_processing_tester.num_channels,
                   expected_height,
                   expected_width,
               )				,			)







     def 						_a      (self				,			__a=False				,			__a=False				,			__a="np"    ):






           '''simple docstring'''



           lowerCamelCase     :   List[Any]								=		self.image_processing_class(**self.image_processor_dict    )
           # prepare image and target
           lowerCamelCase     :   Tuple								=		self.image_processing_tester.num_labels
           lowerCamelCase     :   str								=		None
           lowerCamelCase     :   List[str]								=		None
           lowerCamelCase     :   int								=		prepare_image_inputs(self.image_processing_tester				,			equal_resolution=__a    )
           if with_segmentation_maps:
                 lowerCamelCase     :   str								=		num_labels
                 if is_instance_map:
                       lowerCamelCase     :   Tuple								=		list(range(__a    )    ) * 2
                       lowerCamelCase     :   Tuple								=		dict(enumerate(__a    )    )
                 lowerCamelCase     :   Tuple								=		[
                     np.random.randint(0				,			high * 2				,			(img.size[1], img.size[0])    ).astype(np.uinta    ) for img in image_inputs
                 ]
                 if segmentation_type == "pil":
                       lowerCamelCase     :   Union[str, Any]								=		[Image.fromarray(__a    ) for annotation in annotations]

           lowerCamelCase     :   Optional[Any]								=		image_processor(
               __a				,			["semantic"] * len(__a    )				,			__a				,			return_tensors="pt"				,			instance_id_to_semantic_id=__a				,			pad_and_return_pixel_mask=__a				,			)

           return inputs







     def 						_a      (self    ):






           '''simple docstring'''



           pass







     def 						_a      (self    ):






           '''simple docstring'''



           def common(__a=False				,			__a=None    ):
                 lowerCamelCase     :   List[Any]								=		self.comm_get_image_processor_inputs(
                     with_segmentation_maps=__a				,			is_instance_map=__a				,			segmentation_type=__a    )

                 lowerCamelCase     :   str								=		inputs["mask_labels"]
                 lowerCamelCase     :   Union[str, Any]								=		inputs["class_labels"]
                 lowerCamelCase     :   List[str]								=		inputs["pixel_values"]
                 lowerCamelCase     :   Optional[Any]								=		inputs["text_inputs"]

                 # check the batch_size
                 for mask_label, class_label, text_input in zip(__a				,			__a				,			__a    ):
                       self.assertEqual(mask_label.shape[0]				,			class_label.shape[0]    )
                       # this ensure padding has happened
                       self.assertEqual(mask_label.shape[1:]				,			pixel_values.shape[2:]    )
                       self.assertEqual(len(__a    )				,			self.image_processing_tester.num_text    )

           common()
           common(is_instance_map=__a    )
           common(is_instance_map=__a				,			segmentation_type="pil"    )
           common(is_instance_map=__a				,			segmentation_type="pil"    )







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase     :   List[str]								=		np.zeros((20, 50)    )
           lowerCamelCase     :   List[str]								=		1
           lowerCamelCase     :   Union[str, Any]								=		1
           lowerCamelCase     :   Optional[int]								=		1

           lowerCamelCase     :   int								=		binary_mask_to_rle(__a    )
           self.assertEqual(len(__a    )				,			4    )
           self.assertEqual(rle[0]				,			21    )
           self.assertEqual(rle[1]				,			45    )







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase     :   int								=		self.image_processing_class(
               num_labels=self.image_processing_tester.num_classes				,			max_seq_length=77				,			task_seq_length=77				,			class_info_file="ade20k_panoptic.json"				,			num_text=self.image_processing_tester.num_text				,			repo_path="shi-labs/oneformer_demo"				,			)
           lowerCamelCase     :   Dict								=		self.image_processing_tester.get_fake_oneformer_outputs()

           lowerCamelCase     :   Dict								=		fature_extractor.post_process_semantic_segmentation(__a    )

           self.assertEqual(len(__a    )				,			self.image_processing_tester.batch_size    )
           self.assertEqual(
               segmentation[0].shape				,			(
                   self.image_processing_tester.height,
                   self.image_processing_tester.width,
               )				,			)

           lowerCamelCase     :   Dict								=		[(1, 4) for i in range(self.image_processing_tester.batch_size    )]
           lowerCamelCase     :   List[str]								=		fature_extractor.post_process_semantic_segmentation(__a				,			target_sizes=__a    )

           self.assertEqual(segmentation[0].shape				,			target_sizes[0]    )







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase     :   Optional[int]								=		self.image_processing_class(
               num_labels=self.image_processing_tester.num_classes				,			max_seq_length=77				,			task_seq_length=77				,			class_info_file="ade20k_panoptic.json"				,			num_text=self.image_processing_tester.num_text				,			repo_path="shi-labs/oneformer_demo"				,			)
           lowerCamelCase     :   Any								=		self.image_processing_tester.get_fake_oneformer_outputs()
           lowerCamelCase     :   Tuple								=		image_processor.post_process_instance_segmentation(__a				,			threshold=0    )

           self.assertTrue(len(__a    ) == self.image_processing_tester.batch_size    )
           for el in segmentation:
                 self.assertTrue("segmentation" in el    )
                 self.assertTrue("segments_info" in el    )
                 self.assertEqual(type(el["segments_info"]    )				,			__a    )
                 self.assertEqual(
                     el["segmentation"].shape				,			(self.image_processing_tester.height, self.image_processing_tester.width)    )







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase     :   Optional[int]								=		self.image_processing_class(
               num_labels=self.image_processing_tester.num_classes				,			max_seq_length=77				,			task_seq_length=77				,			class_info_file="ade20k_panoptic.json"				,			num_text=self.image_processing_tester.num_text				,			repo_path="shi-labs/oneformer_demo"				,			)
           lowerCamelCase     :   int								=		self.image_processing_tester.get_fake_oneformer_outputs()
           lowerCamelCase     :   Optional[int]								=		image_processor.post_process_panoptic_segmentation(__a				,			threshold=0    )

           self.assertTrue(len(__a    ) == self.image_processing_tester.batch_size    )
           for el in segmentation:
                 self.assertTrue("segmentation" in el    )
                 self.assertTrue("segments_info" in el    )
                 self.assertEqual(type(el["segments_info"]    )				,			__a    )
                 self.assertEqual(
                     el["segmentation"].shape				,			(self.image_processing_tester.height, self.image_processing_tester.width)    )




from __future__ import annotations

import unittest

from transformers import is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
     import numpy
     import tensorflow as tf

     from transformers import (
         TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
         TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
         TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST,
         BertConfig,
         DPRConfig,
         TFDPRContextEncoder,
         TFDPRQuestionEncoder,
         TFDPRReader,
     )





class    lowerCamelCase__  :
     """simple docstring"""



     def __init__(self				,			__a				,			__a=13				,			__a=7				,			__a=True				,			__a=True				,			__a=True				,			__a=True				,			__a=99				,			__a=32				,			__a=2				,			__a=4				,			__a=37				,			__a="gelu"				,			__a=0.1				,			__a=0.1				,			__a=5_12				,			__a=16				,			__a=2				,			__a=0.02				,			__a=3				,			__a=4				,			__a=None				,			__a=0				,			):






           '''simple docstring'''



           lowerCamelCase								=		parent
           lowerCamelCase								=		batch_size
           lowerCamelCase								=		seq_length
           lowerCamelCase								=		is_training
           lowerCamelCase								=		use_input_mask
           lowerCamelCase								=		use_token_type_ids
           lowerCamelCase								=		use_labels
           lowerCamelCase								=		vocab_size
           lowerCamelCase								=		hidden_size
           lowerCamelCase								=		num_hidden_layers
           lowerCamelCase								=		num_attention_heads
           lowerCamelCase								=		intermediate_size
           lowerCamelCase								=		hidden_act
           lowerCamelCase								=		hidden_dropout_prob
           lowerCamelCase								=		attention_probs_dropout_prob
           lowerCamelCase								=		max_position_embeddings
           lowerCamelCase								=		type_vocab_size
           lowerCamelCase								=		type_sequence_label_size
           lowerCamelCase								=		initializer_range
           lowerCamelCase								=		num_labels
           lowerCamelCase								=		num_choices
           lowerCamelCase								=		scope
           lowerCamelCase								=		projection_dim







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		ids_tensor([self.batch_size, self.seq_length]				,			self.vocab_size    )

           lowerCamelCase								=		None
           if self.use_input_mask:
                 # follow test_modeling_tf_ctrl.py
                 lowerCamelCase								=		random_attention_mask([self.batch_size, self.seq_length]    )

           lowerCamelCase								=		None
           if self.use_token_type_ids:
                 lowerCamelCase								=		ids_tensor([self.batch_size, self.seq_length]				,			self.type_vocab_size    )

           lowerCamelCase								=		None
           lowerCamelCase								=		None
           lowerCamelCase								=		None
           if self.use_labels:
                 lowerCamelCase								=		ids_tensor([self.batch_size]				,			self.type_sequence_label_size    )
                 lowerCamelCase								=		ids_tensor([self.batch_size, self.seq_length]				,			self.num_labels    )
                 lowerCamelCase								=		ids_tensor([self.batch_size]				,			self.num_choices    )

           lowerCamelCase								=		BertConfig(
               vocab_size=self.vocab_size				,			hidden_size=self.hidden_size				,			num_hidden_layers=self.num_hidden_layers				,			num_attention_heads=self.num_attention_heads				,			intermediate_size=self.intermediate_size				,			hidden_act=self.hidden_act				,			hidden_dropout_prob=self.hidden_dropout_prob				,			attention_probs_dropout_prob=self.attention_probs_dropout_prob				,			max_position_embeddings=self.max_position_embeddings				,			type_vocab_size=self.type_vocab_size				,			is_decoder=__a				,			initializer_range=self.initializer_range				,			)
           lowerCamelCase								=		DPRConfig(projection_dim=self.projection_dim				,			**config.to_dict()    )

           return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels







     def 						_a      (self				,			__a				,			__a				,			__a				,			__a				,			__a				,			__a				,			__a    ):






           '''simple docstring'''



           lowerCamelCase								=		TFDPRContextEncoder(config=__a    )
           lowerCamelCase								=		model(__a				,			attention_mask=__a				,			token_type_ids=__a    )
           lowerCamelCase								=		model(__a				,			token_type_ids=__a    )
           lowerCamelCase								=		model(__a    )
           self.parent.assertEqual(result.pooler_output.shape				,			(self.batch_size, self.projection_dim or self.hidden_size)    )







     def 						_a      (self				,			__a				,			__a				,			__a				,			__a				,			__a				,			__a				,			__a    ):






           '''simple docstring'''



           lowerCamelCase								=		TFDPRQuestionEncoder(config=__a    )
           lowerCamelCase								=		model(__a				,			attention_mask=__a				,			token_type_ids=__a    )
           lowerCamelCase								=		model(__a				,			token_type_ids=__a    )
           lowerCamelCase								=		model(__a    )
           self.parent.assertEqual(result.pooler_output.shape				,			(self.batch_size, self.projection_dim or self.hidden_size)    )







     def 						_a      (self				,			__a				,			__a				,			__a				,			__a				,			__a				,			__a				,			__a    ):






           '''simple docstring'''



           lowerCamelCase								=		TFDPRReader(config=__a    )
           lowerCamelCase								=		model(__a				,			attention_mask=__a    )

           self.parent.assertEqual(result.start_logits.shape				,			(self.batch_size, self.seq_length)    )
           self.parent.assertEqual(result.end_logits.shape				,			(self.batch_size, self.seq_length)    )
           self.parent.assertEqual(result.relevance_logits.shape				,			(self.batch_size,)    )







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		self.prepare_config_and_inputs()
           (
               (
               lowerCamelCase
           )			,							(
               lowerCamelCase
           )			,							(
               lowerCamelCase
           )			,							(
               lowerCamelCase
           )			,							(
               lowerCamelCase
           )			,							(
               lowerCamelCase
           )			,							(
               lowerCamelCase
           )			,							
           )								=		config_and_inputs
           lowerCamelCase								=		{"input_ids": input_ids}
           return config, inputs_dict





@require_tf
class    lowerCamelCase__  (						UpperCAmelCase_       ,    UpperCAmelCase_       ,    unittest.TestCase):
     """simple docstring"""



     _A       =			(
         (
             TFDPRContextEncoder,
             TFDPRQuestionEncoder,
             TFDPRReader,
         )
         if is_tf_available()
         else ()
     )
     _A       =			{'feature-extraction': TFDPRQuestionEncoder} if is_tf_available() else {}

     _A       =			False
     _A       =			False
     _A       =			False
     _A       =			False
     _A       =			False







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		TFDPRModelTester(self    )
           lowerCamelCase								=		ConfigTester(self				,			config_class=__a				,			hidden_size=37    )







     def 						_a      (self    ):






           '''simple docstring'''



           self.config_tester.run_common_tests()







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_dpr_context_encoder(*__a    )







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_dpr_question_encoder(*__a    )







     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_dpr_reader(*__a    )







     @slow
     def 						_a      (self    ):






           '''simple docstring'''



           for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 lowerCamelCase								=		TFDPRContextEncoder.from_pretrained(__a    )
                 self.assertIsNotNone(__a    )

           for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 lowerCamelCase								=		TFDPRContextEncoder.from_pretrained(__a    )
                 self.assertIsNotNone(__a    )

           for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 lowerCamelCase								=		TFDPRQuestionEncoder.from_pretrained(__a    )
                 self.assertIsNotNone(__a    )

           for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 lowerCamelCase								=		TFDPRReader.from_pretrained(__a    )
                 self.assertIsNotNone(__a    )





@require_tf
class    lowerCamelCase__  (						unittest.TestCase):
     """simple docstring"""



     @slow
     def 						_a      (self    ):






           '''simple docstring'''



           lowerCamelCase								=		TFDPRQuestionEncoder.from_pretrained("facebook/dpr-question_encoder-single-nq-base"    )

           lowerCamelCase								=		tf.constant(
               [[1_01, 75_92, 10_10, 20_03, 20_26, 38_99, 1_01_40, 10_29, 1_02]]    )  # [CLS] hello, is my dog cute? [SEP]
           lowerCamelCase								=		model(__a    )[0]  # embedding shape = (1, 768)
           # compare the actual values for a slice.
           lowerCamelCase								=		tf.constant(
               [
                   [
                       0.0323_6253,
                       0.1275_3335,
                       0.1681_8509,
                       0.0027_9786,
                       0.389_6933,
                       0.2426_4945,
                       0.217_8971,
                       -0.0233_5227,
                       -0.0848_1959,
                       -0.1432_4117,
                   ]
               ]    )
           self.assertTrue(numpy.allclose(output[:, :10].numpy()				,			expected_slice.numpy()				,			atol=1E-4    )    )