
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 		UpperCamelCase__  :
   def __init__(self			: Optional[int] ,    snake_case_			: List[Any] ,    snake_case_			: Union[str, Any]=1_3 ,    snake_case_			: List[Any]=7 ,    snake_case_			: Tuple=True ,    snake_case_			: Tuple=True ,    snake_case_			: Any=True ,    snake_case_			: Dict=True ,    snake_case_			: str=9_9 ,    snake_case_			: Dict=3_2 ,    snake_case_			: Union[str, Any]=2 ,    snake_case_			: List[Any]=4 ,    snake_case_			: List[Any]=3_7 ,    snake_case_			: Union[str, Any]="gelu" ,    snake_case_			: List[str]=0.1 ,    snake_case_			: Tuple=0.1 ,    snake_case_			: Optional[int]=5_1_2 ,    snake_case_			: Optional[int]=1_6 ,    snake_case_			: Dict=2 ,    snake_case_			: int=0.02 ,    snake_case_			: Optional[Any]=3 ,    snake_case_			: Union[str, Any]=4 ,    snake_case_			: Tuple=None ,    snake_case_			: str=0 ,    ):
          __a			:  Dict		    =  parent
          __a			:  int		    =  batch_size
          __a			:  str		    =  seq_length
          __a			:  Optional[int]		    =  is_training
          __a			:  Union[str, Any]		    =  use_input_mask
          __a			:  Union[str, Any]		    =  use_token_type_ids
          __a			:  Optional[Any]		    =  use_labels
          __a			:  Union[str, Any]		    =  vocab_size
          __a			:  str		    =  hidden_size
          __a			:  List[str]		    =  num_hidden_layers
          __a			:  int		    =  num_attention_heads
          __a			:  Optional[int]		    =  intermediate_size
          __a			:  Tuple		    =  hidden_act
          __a			:  Tuple		    =  hidden_dropout_prob
          __a			:  str		    =  attention_probs_dropout_prob
          __a			:  int		    =  max_position_embeddings
          __a			:  Dict		    =  type_vocab_size
          __a			:  str		    =  type_sequence_label_size
          __a			:  Optional[int]		    =  initializer_range
          __a			:  int		    =  num_labels
          __a			:  List[Any]		    =  num_choices
          __a			:  List[Any]		    =  scope
          __a			:  Optional[int]		    =  projection_dim
   def 				lowerCAmelCase      (self			: Any       ):
          __a			:  List[str]		    =  ids_tensor([self.batch_size, self.seq_length] ,    self.vocab_size       )

          __a			:  List[str]		    =  None
          if self.use_input_mask:
                 # follow test_modeling_tf_ctrl.py
                 __a			:  Optional[Any]		    =  random_attention_mask([self.batch_size, self.seq_length]       )

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

          __a			:  Any		    =  None
          __a			:  Optional[int]		    =  None
          __a			:  Optional[int]		    =  None
          if self.use_labels:
                 __a			:  Optional[Any]		    =  ids_tensor([self.batch_size] ,    self.type_sequence_label_size       )
                 __a			:  str		    =  ids_tensor([self.batch_size, self.seq_length] ,    self.num_labels       )
                 __a			:  Optional[Any]		    =  ids_tensor([self.batch_size] ,    self.num_choices       )

          __a			:  Optional[Any]		    =  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=snake_case_ ,    initializer_range=self.initializer_range ,    )
          __a			:  List[str]		    =  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 				lowerCAmelCase      (self			: str ,    snake_case_			: List[str] ,    snake_case_			: int ,    snake_case_			: Union[str, Any] ,    snake_case_			: List[Any] ,    snake_case_			: Dict ,    snake_case_			: str ,    snake_case_			: List[Any]       ):
          __a			:  int		    =  TFDPRContextEncoder(config=snake_case_       )
          __a			:  Union[str, Any]		    =  model(snake_case_ ,    attention_mask=snake_case_ ,    token_type_ids=snake_case_       )
          __a			:  Union[str, Any]		    =  model(snake_case_ ,    token_type_ids=snake_case_       )
          __a			:  List[Any]		    =  model(snake_case_       )
          self.parent.assertEqual(result.pooler_output.shape ,    (self.batch_size, self.projection_dim or self.hidden_size)       )
   def 				lowerCAmelCase      (self			: Tuple ,    snake_case_			: Optional[Any] ,    snake_case_			: List[str] ,    snake_case_			: List[str] ,    snake_case_			: Tuple ,    snake_case_			: Optional[int] ,    snake_case_			: Any ,    snake_case_			: Optional[int]       ):
          __a			:  List[str]		    =  TFDPRQuestionEncoder(config=snake_case_       )
          __a			:  Dict		    =  model(snake_case_ ,    attention_mask=snake_case_ ,    token_type_ids=snake_case_       )
          __a			:  Optional[Any]		    =  model(snake_case_ ,    token_type_ids=snake_case_       )
          __a			:  List[str]		    =  model(snake_case_       )
          self.parent.assertEqual(result.pooler_output.shape ,    (self.batch_size, self.projection_dim or self.hidden_size)       )
   def 				lowerCAmelCase      (self			: Union[str, Any] ,    snake_case_			: List[str] ,    snake_case_			: Any ,    snake_case_			: int ,    snake_case_			: int ,    snake_case_			: Tuple ,    snake_case_			: List[str] ,    snake_case_			: Optional[Any]       ):
          __a			:  List[Any]		    =  TFDPRReader(config=snake_case_       )
          __a			:  int		    =  model(snake_case_ ,    attention_mask=snake_case_       )

          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 				lowerCAmelCase      (self			: str       ):
          __a			:  List[str]		    =  self.prepare_config_and_inputs()
          (
              __a  
          )			:  Optional[int]		    =  config_and_inputs
          __a			:  Dict		    =  {"input_ids": input_ids}
          return config, inputs_dict





@require_tf
class 		UpperCamelCase__  (	lowerCamelCase__   ,lowerCamelCase__   ,unittest.TestCase   ):
   _SCREAMING_SNAKE_CASE				:							List[str]     	=				(
       (
           TFDPRContextEncoder,
           TFDPRQuestionEncoder,
           TFDPRReader,
       )
       if is_tf_available()
       else ()
   )
   _SCREAMING_SNAKE_CASE				:							str     	=				{"feature-extraction": TFDPRQuestionEncoder} if is_tf_available() else {}

   _SCREAMING_SNAKE_CASE				:							List[str]     	=				False
   _SCREAMING_SNAKE_CASE				:							Union[str, Any]     	=				False
   _SCREAMING_SNAKE_CASE				:							List[Any]     	=				False
   _SCREAMING_SNAKE_CASE				:							List[str]     	=				False
   _SCREAMING_SNAKE_CASE				:							str     	=				False
   def 				lowerCAmelCase      (self			: Optional[int]       ):
          __a			:  Any		    =  TFDPRModelTester(self       )
          __a			:  Dict		    =  ConfigTester(self ,    config_class=snake_case_ ,    hidden_size=3_7       )
   def 				lowerCAmelCase      (self			: Optional[Any]       ):
          self.config_tester.run_common_tests()
   def 				lowerCAmelCase      (self			: List[str]       ):
          __a			:  str		    =  self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_dpr_context_encoder(*snake_case_       )
   def 				lowerCAmelCase      (self			: int       ):
          __a			:  str		    =  self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_dpr_question_encoder(*snake_case_       )
   def 				lowerCAmelCase      (self			: List[Any]       ):
          __a			:  Union[str, Any]		    =  self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_dpr_reader(*snake_case_       )







   @slow
   def 				lowerCAmelCase      (self			: Union[str, Any]       ):




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

          for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 __a			:  Union[str, Any]		    =  TFDPRContextEncoder.from_pretrained(snake_case_       )
                 self.assertIsNotNone(snake_case_       )

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

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





@require_tf
class 		UpperCamelCase__  (	unittest.TestCase   ):
   @slow
   def 				lowerCAmelCase      (self			: Optional[Any]       ):
          __a			:  int		    =  TFDPRQuestionEncoder.from_pretrained('''facebook/dpr-question_encoder-single-nq-base'''       )

          __a			:  Union[str, Any]		    =  tf.constant(
              [[1_0_1, 7_5_9_2, 1_0_1_0, 2_0_0_3, 2_0_2_6, 3_8_9_9, 1_0_1_4_0, 1_0_2_9, 1_0_2]]       )  # [CLS] hello, is my dog cute? [SEP]
          __a			:  List[Any]		    =  model(snake_case_       )[0]  # embedding shape = (1, 768)
          # compare the actual values for a slice.
          __a			:  str		    =  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[:, :1_0].numpy() ,    expected_slice.numpy() ,    atol=1E-4       )       )


# Copyright 2023 The HuggingFace 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 typing import TYPE_CHECKING

# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


lowercase__          ={
    'configuration_efficientnet': [
        'EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP',
        'EfficientNetConfig',
        'EfficientNetOnnxConfig',
    ]
}

try:
      if not is_vision_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      lowercase__          =['EfficientNetImageProcessor']

try:
      if not is_torch_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      lowercase__          =[
          'EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST',
          'EfficientNetForImageClassification',
          'EfficientNetModel',
          'EfficientNetPreTrainedModel',
      ]

if TYPE_CHECKING:
      from .configuration_efficientnet import (
          EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP,
          EfficientNetConfig,
          EfficientNetOnnxConfig,
      )

      try:
            if not is_vision_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .image_processing_efficientnet import EfficientNetImageProcessor

      try:
            if not is_torch_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_efficientnet import (
                EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST,
                EfficientNetForImageClassification,
                EfficientNetModel,
                EfficientNetPreTrainedModel,
            )

else:
      import sys

      lowercase__          =_LazyModule(__name__, globals()['__file__'], _import_structure)
