

from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import SwinConfig
from transformers.testing_utils import require_tf, require_vision, slow, to_atuple
from transformers.utils import cached_property, is_tf_available, is_vision_available

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


if is_tf_available():
       import tensorflow as tf

       from transformers.models.swin.modeling_tf_swin import (
           TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST,
           TFSwinForImageClassification,
           TFSwinForMaskedImageModeling,
           TFSwinModel,
       )


if is_vision_available():
       from PIL import Image

       from transformers import AutoImageProcessor
class     SCREAMING_SNAKE_CASE__     :





       '''simple docstring'''




       def __init__(						self       :						List[Any]    ,		lowerCAmelCase__       :						int    ,		lowerCAmelCase__       :						int=13    ,		lowerCAmelCase__       :						Union[str, Any]=32    ,		lowerCAmelCase__       :						Union[str, Any]=2    ,		lowerCAmelCase__       :						Tuple=3    ,		lowerCAmelCase__       :						Union[str, Any]=16    ,		lowerCAmelCase__       :						Union[str, Any]=[1, 2, 1]    ,		lowerCAmelCase__       :						Tuple=[2, 2, 4]    ,		lowerCAmelCase__       :						Dict=2    ,		lowerCAmelCase__       :						Optional[Any]=2.0    ,		lowerCAmelCase__       :						int=True    ,		lowerCAmelCase__       :						Optional[Any]=0.0    ,		lowerCAmelCase__       :						int=0.0    ,		lowerCAmelCase__       :						Any=0.1    ,		lowerCAmelCase__       :						List[Any]="gelu"    ,		lowerCAmelCase__       :						List[str]=False    ,		lowerCAmelCase__       :						Optional[Any]=True    ,		lowerCAmelCase__       :						Optional[int]=0.02    ,		lowerCAmelCase__       :						Optional[Any]=1E-5    ,		lowerCAmelCase__       :						Tuple=True    ,		lowerCAmelCase__       :						Optional[int]=None    ,		lowerCAmelCase__       :						Optional[Any]=True    ,		lowerCAmelCase__       :						Optional[int]=10    ,		lowerCAmelCase__       :						Optional[int]=8    ,		)			->    None:
             snake_case__					=   parent
             snake_case__					=   batch_size
             snake_case__					=   image_size
             snake_case__					=   patch_size
             snake_case__					=   num_channels
             snake_case__					=   embed_dim
             snake_case__					=   depths
             snake_case__					=   num_heads
             snake_case__					=   window_size
             snake_case__					=   mlp_ratio
             snake_case__					=   qkv_bias
             snake_case__					=   hidden_dropout_prob
             snake_case__					=   attention_probs_dropout_prob
             snake_case__					=   drop_path_rate
             snake_case__					=   hidden_act
             snake_case__					=   use_absolute_embeddings
             snake_case__					=   patch_norm
             snake_case__					=   layer_norm_eps
             snake_case__					=   initializer_range
             snake_case__					=   is_training
             snake_case__					=   scope
             snake_case__					=   use_labels
             snake_case__					=   type_sequence_label_size
             snake_case__					=   encoder_stride

       def UpperCAmelCase_						(						self       :						Tuple							)			->    Union[str, Any]:
             snake_case__					=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

             snake_case__					=   None
             if self.use_labels:
                   snake_case__					=   ids_tensor([self.batch_size]    ,		self.type_sequence_label_size							)

             snake_case__					=   self.get_config()

             return config, pixel_values, labels

       def UpperCAmelCase_						(						self       :						Optional[int]							)			->    List[str]:
             return SwinConfig(
                 image_size=self.image_size    ,		patch_size=self.patch_size    ,		num_channels=self.num_channels    ,		embed_dim=self.embed_dim    ,		depths=self.depths    ,		num_heads=self.num_heads    ,		window_size=self.window_size    ,		mlp_ratio=self.mlp_ratio    ,		qkv_bias=self.qkv_bias    ,		hidden_dropout_prob=self.hidden_dropout_prob    ,		attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,		drop_path_rate=self.drop_path_rate    ,		hidden_act=self.hidden_act    ,		use_absolute_embeddings=self.use_absolute_embeddings    ,		path_norm=self.patch_norm    ,		layer_norm_eps=self.layer_norm_eps    ,		initializer_range=self.initializer_range    ,		encoder_stride=self.encoder_stride    ,		)

       def UpperCAmelCase_						(						self       :						Tuple    ,		lowerCAmelCase__       :						List[Any]    ,		lowerCAmelCase__       :						Any    ,		lowerCAmelCase__       :						str							)			->    Dict:
             snake_case__					=   TFSwinModel(config=lowerCAmelCase__							)
             snake_case__					=   model(lowerCAmelCase__							)

             snake_case__					=   ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths							) - 1))
             snake_case__					=   int(config.embed_dim * 2 ** (len(config.depths							) - 1)							)

             self.parent.assertEqual(result.last_hidden_state.shape    ,		(self.batch_size, expected_seq_len, expected_dim)							)

       def UpperCAmelCase_						(						self       :						Union[str, Any]    ,		lowerCAmelCase__       :						int    ,		lowerCAmelCase__       :						Tuple    ,		lowerCAmelCase__       :						Tuple							)			->    Optional[int]:
             snake_case__					=   TFSwinForMaskedImageModeling(config=lowerCAmelCase__							)
             snake_case__					=   model(lowerCAmelCase__							)
             self.parent.assertEqual(
                 result.logits.shape    ,		(self.batch_size, self.num_channels, self.image_size, self.image_size)							)

             # test greyscale images
             snake_case__					=   1
             snake_case__					=   TFSwinForMaskedImageModeling(lowerCAmelCase__							)

             snake_case__					=   floats_tensor([self.batch_size, 1, self.image_size, self.image_size]							)
             snake_case__					=   model(lowerCAmelCase__							)
             self.parent.assertEqual(result.logits.shape    ,		(self.batch_size, 1, self.image_size, self.image_size)							)

       def UpperCAmelCase_						(						self       :						str    ,		lowerCAmelCase__       :						Tuple    ,		lowerCAmelCase__       :						List[Any]    ,		lowerCAmelCase__       :						int							)			->    str:
             snake_case__					=   self.type_sequence_label_size
             snake_case__					=   TFSwinForImageClassification(lowerCAmelCase__							)
             snake_case__					=   model(lowerCAmelCase__    ,		labels=lowerCAmelCase__							)
             self.parent.assertEqual(result.logits.shape    ,		(self.batch_size, self.type_sequence_label_size)							)

             # test greyscale images
             snake_case__					=   1
             snake_case__					=   TFSwinForImageClassification(lowerCAmelCase__							)
             snake_case__					=   floats_tensor([self.batch_size, 1, self.image_size, self.image_size]							)
             snake_case__					=   model(lowerCAmelCase__							)
             self.parent.assertEqual(result.logits.shape    ,		(self.batch_size, self.type_sequence_label_size)							)

       def UpperCAmelCase_						(						self       :						int							)			->    int:
             snake_case__					=   self.prepare_config_and_inputs()
             snake_case__	,			snake_case__	,			snake_case__					=   config_and_inputs
             snake_case__					=   {"""pixel_values""": pixel_values}
             return config, inputs_dict



@require_tf
class     SCREAMING_SNAKE_CASE__     (						__a ,	__a ,	unittest.TestCase		):





       '''simple docstring'''




       UpperCamelCase__ :     Optional[Any]				    =       (
           (
               TFSwinModel,
               TFSwinForImageClassification,
               TFSwinForMaskedImageModeling,
           )
           if is_tf_available()
           else ()
       )
       UpperCamelCase__ :     Dict				    =       (
           {'''feature-extraction''': TFSwinModel, '''image-classification''': TFSwinForImageClassification}
           if is_tf_available()
           else {}
       )

       UpperCamelCase__ :     Dict				    =       False
       UpperCamelCase__ :     List[str]				    =       False
       UpperCamelCase__ :     Optional[Any]				    =       False
       UpperCamelCase__ :     Optional[Any]				    =       False

       def UpperCAmelCase_						(						self       :						Union[str, Any]							)			->    Any:
             snake_case__					=   TFSwinModelTester(self							)
             snake_case__					=   ConfigTester(self    ,		config_class=lowerCAmelCase__    ,		embed_dim=37							)

       def UpperCAmelCase_						(						self       :						str							)			->    List[Any]:
             self.create_and_test_config_common_properties()
             self.config_tester.create_and_test_config_to_json_string()
             self.config_tester.create_and_test_config_to_json_file()
             self.config_tester.create_and_test_config_from_and_save_pretrained()
             self.config_tester.create_and_test_config_with_num_labels()
             self.config_tester.check_config_can_be_init_without_params()
             self.config_tester.check_config_arguments_init()

       def UpperCAmelCase_						(						self       :						Tuple							)			->    List[Any]:
             return

       def UpperCAmelCase_						(						self       :						str							)			->    Optional[int]:
             snake_case__					=   self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*lowerCAmelCase__							)

       def UpperCAmelCase_						(						self       :						Union[str, Any]							)			->    Dict:
             snake_case__					=   self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_masked_image_modeling(*lowerCAmelCase__							)

       def UpperCAmelCase_						(						self       :						Dict							)			->    List[Any]:
             snake_case__					=   self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__							)

       @unittest.skip(reason="""Swin does not use inputs_embeds"""							)
       def UpperCAmelCase_						(						self       :						Optional[Any]							)			->    int:
             pass

       def UpperCAmelCase_						(						self       :						List[Any]							)			->    Tuple:
             snake_case__	,			snake_case__					=   self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                   snake_case__					=   model_class(lowerCAmelCase__							)
                   self.assertIsInstance(model.get_input_embeddings()    ,		tf.keras.layers.Layer							)
                   snake_case__					=   model.get_output_embeddings()
                   self.assertTrue(x is None or isinstance(lowerCAmelCase__    ,		tf.keras.layers.Dense							)							)

       def UpperCAmelCase_						(						self       :						Optional[Any]							)			->    Union[str, Any]:
             snake_case__	,			snake_case__					=   self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                   snake_case__					=   model_class(lowerCAmelCase__							)
                   snake_case__					=   inspect.signature(model.call							)
                   # signature.parameters is an OrderedDict => so arg_names order is deterministic
                   snake_case__					=   [*signature.parameters.keys()]

                   snake_case__					=   ["""pixel_values"""]
                   self.assertListEqual(arg_names[:1]    ,		lowerCAmelCase__							)

       def UpperCAmelCase_						(						self       :						Union[str, Any]							)			->    Tuple:
             snake_case__	,			snake_case__					=   self.model_tester.prepare_config_and_inputs_for_common()
             snake_case__					=   True

             for model_class in self.all_model_classes:
                   snake_case__					=   True
                   snake_case__					=   False
                   snake_case__					=   True
                   snake_case__					=   model_class(lowerCAmelCase__							)
                   snake_case__					=   model(**self._prepare_for_class(lowerCAmelCase__    ,		lowerCAmelCase__							)							)
                   snake_case__					=   outputs.attentions
                   snake_case__					=   len(self.model_tester.depths							)
                   self.assertEqual(len(lowerCAmelCase__							)    ,		lowerCAmelCase__							)

                   # check that output_attentions also work using config
                   del inputs_dict["output_attentions"]
                   snake_case__					=   True
                   snake_case__					=   config.window_size**2
                   snake_case__					=   model_class(lowerCAmelCase__							)
                   snake_case__					=   model(**self._prepare_for_class(lowerCAmelCase__    ,		lowerCAmelCase__							)							)
                   snake_case__					=   outputs.attentions
                   self.assertEqual(len(lowerCAmelCase__							)    ,		lowerCAmelCase__							)

                   self.assertListEqual(
                       list(attentions[0].shape[-3:]							)    ,		[self.model_tester.num_heads[0], window_size_squared, window_size_squared]    ,		)
                   snake_case__					=   len(lowerCAmelCase__							)

                   # Check attention is always last and order is fine
                   snake_case__					=   True
                   snake_case__					=   True
                   snake_case__					=   model_class(lowerCAmelCase__							)
                   snake_case__					=   model(**self._prepare_for_class(lowerCAmelCase__    ,		lowerCAmelCase__							)							)

                   if hasattr(self.model_tester    ,		"""num_hidden_states_types"""							):
                         snake_case__					=   self.model_tester.num_hidden_states_types
                   else:
                         # also another +1 for reshaped_hidden_states
                         snake_case__					=   2
                   self.assertEqual(out_len + added_hidden_states    ,		len(lowerCAmelCase__							)							)

                   snake_case__					=   outputs.attentions

                   self.assertEqual(len(lowerCAmelCase__							)    ,		lowerCAmelCase__							)

                   self.assertListEqual(
                       list(self_attentions[0].shape[-3:]							)    ,		[self.model_tester.num_heads[0], window_size_squared, window_size_squared]    ,		)

       def UpperCAmelCase_						(						self       :						int    ,		lowerCAmelCase__       :						List[Any]    ,		lowerCAmelCase__       :						Any    ,		lowerCAmelCase__       :						Tuple    ,		lowerCAmelCase__       :						Optional[Any]							)			->    Tuple:
             snake_case__					=   model_class(lowerCAmelCase__							)
             snake_case__					=   model(**self._prepare_for_class(lowerCAmelCase__    ,		lowerCAmelCase__							)							)
             snake_case__					=   outputs.hidden_states

             snake_case__					=   getattr(
                 self.model_tester    ,		"""expected_num_hidden_layers"""    ,		len(self.model_tester.depths							) + 1							)
             self.assertEqual(len(lowerCAmelCase__							)    ,		lowerCAmelCase__							)

             # Swin has a different seq_length
             snake_case__					=   to_atuple(config.patch_size							)

             snake_case__					=   (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

             self.assertListEqual(
                 list(hidden_states[0].shape[-2:]							)    ,		[num_patches, self.model_tester.embed_dim]    ,		)

             snake_case__					=   outputs.reshaped_hidden_states
             self.assertEqual(len(lowerCAmelCase__							)    ,		lowerCAmelCase__							)

             snake_case__	,			snake_case__	,			snake_case__	,			snake_case__					=   reshaped_hidden_states[0].shape

             snake_case__					=   tf.reshape(reshaped_hidden_states[0]    ,		(batch_size, num_channels, height * width)							)
             snake_case__					=   tf.transpose(lowerCAmelCase__    ,		(0, 2, 1)							)

             self.assertListEqual(
                 list(reshaped_hidden_states.shape[-2:]							)    ,		[num_patches, self.model_tester.embed_dim]    ,		)

       def UpperCAmelCase_						(						self       :						str							)			->    Union[str, Any]:
             snake_case__	,			snake_case__					=   self.model_tester.prepare_config_and_inputs_for_common()

             snake_case__					=   to_atuple(self.model_tester.image_size							)

             for model_class in self.all_model_classes:
                   snake_case__					=   True
                   self.check_hidden_states_output(lowerCAmelCase__    ,		lowerCAmelCase__    ,		lowerCAmelCase__    ,		lowerCAmelCase__							)

                   # check that output_hidden_states also work using config
                   del inputs_dict["output_hidden_states"]
                   snake_case__					=   True

                   self.check_hidden_states_output(lowerCAmelCase__    ,		lowerCAmelCase__    ,		lowerCAmelCase__    ,		lowerCAmelCase__							)

       def UpperCAmelCase_						(						self       :						Optional[int]							)			->    int:
             snake_case__	,			snake_case__					=   self.model_tester.prepare_config_and_inputs_for_common()
             snake_case__					=   3

             snake_case__					=   to_atuple(self.model_tester.image_size							)
             snake_case__					=   to_atuple(config.patch_size							)

             snake_case__					=   image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
             snake_case__					=   image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

             for model_class in self.all_model_classes:
                   snake_case__					=   True
                   self.check_hidden_states_output(lowerCAmelCase__    ,		lowerCAmelCase__    ,		lowerCAmelCase__    ,		(padded_height, padded_width)							)

                   # check that output_hidden_states also work using config
                   del inputs_dict["output_hidden_states"]
                   snake_case__					=   True
                   self.check_hidden_states_output(lowerCAmelCase__    ,		lowerCAmelCase__    ,		lowerCAmelCase__    ,		(padded_height, padded_width)							)

       @slow
       def UpperCAmelCase_						(						self       :						str							)			->    Dict:
             for model_name in TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   snake_case__					=   TFSwinModel.from_pretrained(lowerCAmelCase__							)
                   self.assertIsNotNone(lowerCAmelCase__							)



@require_vision
@require_tf
class     SCREAMING_SNAKE_CASE__     (						unittest.TestCase		):





       '''simple docstring'''




       @cached_property
       def UpperCAmelCase_						(						self       :						int							)			->    Union[str, Any]:
             return (
                 AutoImageProcessor.from_pretrained("""microsoft/swin-tiny-patch4-window7-224"""							)
                 if is_vision_available()
                 else None
             )

       @slow
       def UpperCAmelCase_						(						self       :						int							)			->    int:
             snake_case__					=   TFSwinForImageClassification.from_pretrained("""microsoft/swin-tiny-patch4-window7-224"""							)
             snake_case__					=   self.default_image_processor

             snake_case__					=   Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""							)
             snake_case__					=   image_processor(images=lowerCAmelCase__    ,		return_tensors="""tf"""							)

             # forward pass
             snake_case__					=   model(lowerCAmelCase__							)

             # verify the logits
             snake_case__					=   tf.TensorShape((1, 1000)							)
             self.assertEqual(outputs.logits.shape    ,		lowerCAmelCase__							)
             snake_case__					=   tf.constant([-0.0_948, -0.6_454, -0.0_921]							)
             self.assertTrue(np.allclose(outputs.logits[0, :3]    ,		lowerCAmelCase__    ,		atol=1E-4							)							)









# Copyright 2023 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 ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer
from .base import PipelineTool


lowerCAmelCase						:   List[Any]										=    '''Here is a text containing a lot of information: \'\'\'{text}\'\'\'.

Can you answer this question about the text: \'{question}\''''
class     SCREAMING_SNAKE_CASE__     (						__a		):





       '''simple docstring'''




       UpperCamelCase__ :     int				    =       '''google/flan-t5-base'''
       UpperCamelCase__ :     int				    =       (
           '''This is a tool that answers questions related to a text. It takes two arguments named `text`, which is the '''
           '''text where to find the answer, and `question`, which is the question, and returns the answer to the question.'''
       )
       UpperCamelCase__ :     Tuple				    =       '''text_qa'''
       UpperCamelCase__ :     Tuple				    =       AutoTokenizer
       UpperCamelCase__ :     List[Any]				    =       AutoModelForSeqaSeqLM

       UpperCamelCase__ :     Optional[Any]				    =       ['''text''', '''text''']
       UpperCamelCase__ :     Any				    =       ['''text''']

       def UpperCAmelCase_						(						self       :						Tuple    ,		lowerCAmelCase__       :						str    ,		lowerCAmelCase__       :						str							)			->    List[Any]:
             snake_case__					=   QA_PROMPT.format(text=lowerCAmelCase__    ,		question=lowerCAmelCase__							)
             return self.pre_processor(lowerCAmelCase__    ,		return_tensors="""pt"""							)

       def UpperCAmelCase_						(						self       :						Optional[Any]    ,		lowerCAmelCase__       :						Dict							)			->    List[Any]:
             snake_case__					=   self.model.generate(**lowerCAmelCase__							)

             snake_case__	,			snake_case__					=   inputs["""input_ids"""].shape
             snake_case__					=   output_ids.shape[0]

             return output_ids.reshape(lowerCAmelCase__    ,		out_b // in_b    ,		*output_ids.shape[1:]							)[0][0]

       def UpperCAmelCase_						(						self       :						Union[str, Any]    ,		lowerCAmelCase__       :						Dict							)			->    List[Any]:
             return self.pre_processor.decode(lowerCAmelCase__    ,		skip_special_tokens=lowerCAmelCase__    ,		clean_up_tokenization_spaces=lowerCAmelCase__							)






