






'''simple docstring'''
import inspect
import unittest

import numpy as np

from tests.test_modeling_common import floats_tensor
from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch

 from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel

 if is_vision_available():
  from transformers import MaskFormerImageProcessor

if is_vision_available():
 from PIL import Image


class 							_UpperCAmelCase    :




    def __init__(      self	:							Tuple	,  a	:							Optional[int]	,  a	:							List[Any]=2	,  a	:							List[str]=True	,  a	:							Optional[Any]=False	,  a	:							Any=1_0	,  a	:							Any=3	,  a	:							Optional[Any]=3_2 * 4	,  a	:							str=3_2 * 6	,  a	:							Optional[int]=4	,  a	:							Optional[Any]=3_2	,  ):






       '''simple docstring'''






       lowercase_						:     List[Any]							     =  parent
       lowercase_						:     Any							     =  batch_size
       lowercase_						:     List[str]							     =  is_training
       lowercase_						:     Tuple							     =  use_auxiliary_loss
       lowercase_						:     List[str]							     =  num_queries
       lowercase_						:     int							     =  num_channels
       lowercase_						:     Any							     =  min_size
       lowercase_						:     List[str]							     =  max_size
       lowercase_						:     Tuple							     =  num_labels
       lowercase_						:     Any							     =  mask_feature_size




    def 					lowerCAmelCase__					(      self	:							Any      ):






       '''simple docstring'''






       lowercase_						:     Dict							     =  floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]      ).to(
           a      )

       lowercase_						:     Tuple							     =  torch.ones([self.batch_size, self.min_size, self.max_size]	,  device=a      )

       lowercase_						:     str							     =  (
           torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size]	,  device=a      ) > 0.5
       ).float()
       lowercase_						:     Any							     =  (torch.rand((self.batch_size, self.num_labels)	,  device=a      ) > 0.5).long()

       lowercase_						:     List[str]							     =  self.get_config()
       return config, pixel_values, pixel_mask, mask_labels, class_labels




    def 					lowerCAmelCase__					(      self	:							List[str]      ):






       '''simple docstring'''






       return MaskFormerConfig.from_backbone_and_decoder_configs(
           backbone_config=SwinConfig(
               depths=[1, 1, 1, 1]	,  )	,  decoder_config=DetrConfig(
               decoder_ffn_dim=1_2_8	,  num_queries=self.num_queries	,  decoder_attention_heads=2	,  d_model=self.mask_feature_size	,  )	,  mask_feature_size=self.mask_feature_size	,  fpn_feature_size=self.mask_feature_size	,  num_channels=self.num_channels	,  num_labels=self.num_labels	,  )




    def 					lowerCAmelCase__					(      self	:							Optional[Any]      ):






       '''simple docstring'''






       lowercase_     ,		lowercase_     ,		lowercase_     ,		lowercase_     ,		lowercase_						:     Dict							     =  self.prepare_config_and_inputs()
       lowercase_						:     Optional[int]							     =  {"pixel_values": pixel_values, "pixel_mask": pixel_mask}
       return config, inputs_dict




    def 					lowerCAmelCase__					(      self	:							str	,  a	:							Any	,  a	:							Tuple      ):






       '''simple docstring'''






       lowercase_						:     List[Any]							     =  output.encoder_hidden_states
       lowercase_						:     Optional[int]							     =  output.pixel_decoder_hidden_states
       lowercase_						:     int							     =  output.transformer_decoder_hidden_states

       self.parent.assertTrue(len(a      )	,  len(config.backbone_config.depths      )      )
       self.parent.assertTrue(len(a      )	,  len(config.backbone_config.depths      )      )
       self.parent.assertTrue(len(a      )	,  config.decoder_config.decoder_layers      )




    def 					lowerCAmelCase__					(      self	:							int	,  a	:							List[str]	,  a	:							Optional[Any]	,  a	:							Tuple	,  a	:							int=False      ):






       '''simple docstring'''






       with torch.no_grad():
          lowercase_						:     Union[str, Any]							     =  MaskFormerModel(config=a      )
          model.to(a      )
          model.eval()

          lowercase_						:     str							     =  model(pixel_values=a	,  pixel_mask=a      )
          lowercase_						:     Any							     =  model(a	,  output_hidden_states=a      )
       # the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the
       # encoder and pixel decoder
       self.parent.assertEqual(
           output.transformer_decoder_last_hidden_state.shape	,  (self.batch_size, self.num_queries, self.mask_feature_size)	,  )
       # let's ensure the other two hidden state exists
       self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None      )
       self.parent.assertTrue(output.encoder_last_hidden_state is not None      )

       if output_hidden_states:
          self.check_output_hidden_state(a	,  a      )





    def 					lowerCAmelCase__					(      self	:							int	,  a	:							int	,  a	:							str	,  a	:							Dict	,  a	:							List[str]	,  a	:							Tuple      ):






       '''simple docstring'''






       lowercase_						:     Dict							     =  MaskFormerForInstanceSegmentation(config=a      )
       model.to(a      )
       model.eval()

       def comm_check_on_output(a	:							Tuple      ):
          # let's still check that all the required stuff is there
          self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None      )
          self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None      )
          self.parent.assertTrue(result.encoder_last_hidden_state is not None      )
          # okay, now we need to check the logits shape
          # due to the encoder compression, masks have a //4 spatial size
          self.parent.assertEqual(
              result.masks_queries_logits.shape	,  (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4)	,  )
          # + 1 for null class
          self.parent.assertEqual(
              result.class_queries_logits.shape	,  (self.batch_size, self.num_queries, self.num_labels + 1)      )

       with torch.no_grad():
          lowercase_						:     Any							     =  model(pixel_values=a	,  pixel_mask=a      )
          lowercase_						:     Union[str, Any]							     =  model(a      )

          comm_check_on_output(a      )

          lowercase_						:     Optional[int]							     =  model(
              pixel_values=a	,  pixel_mask=a	,  mask_labels=a	,  class_labels=a      )

       comm_check_on_output(a      )

       self.parent.assertTrue(result.loss is not None      )
       self.parent.assertEqual(result.loss.shape	,  torch.Size([1]      )      )


@require_torch
class 							_UpperCAmelCase    (		snake_case					,       snake_case					,       unittest.TestCase      ):
    __lowerCamelCase: int									=     (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else ()
    __lowerCamelCase: Optional[int]									=     (
        {'feature-extraction': MaskFormerModel, 'image-segmentation': MaskFormerForInstanceSegmentation}
        if is_torch_available()
        else {}
    )

    __lowerCamelCase: Optional[int]									=     False
    __lowerCamelCase: List[str]									=     False
    __lowerCamelCase: List[Any]									=     False
    __lowerCamelCase: Optional[int]									=     False




    def 					lowerCAmelCase__					(      self	:							Any      ):






       '''simple docstring'''






       lowercase_						:     Union[str, Any]							     =  MaskFormerModelTester(self      )
       lowercase_						:     Optional[int]							     =  ConfigTester(self	,  config_class=a	,  has_text_modality=a      )




    def 					lowerCAmelCase__					(      self	:							Any      ):






       '''simple docstring'''






       self.config_tester.run_common_tests()




    def 					lowerCAmelCase__					(      self	:							Any      ):






       '''simple docstring'''






       lowercase_     ,		lowercase_						:     Tuple							     =  self.model_tester.prepare_config_and_inputs_for_common()
       self.model_tester.create_and_check_maskformer_model(a	,  **a	,  output_hidden_states=a      )




    def 					lowerCAmelCase__					(      self	:							Tuple      ):






       '''simple docstring'''






       lowercase_						:     List[Any]							     =  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*a      )




    @unittest.skip(reason="MaskFormer does not use inputs_embeds"      )
    def 					lowerCAmelCase__					(      self	:							Union[str, Any]      ):






       '''simple docstring'''






       pass




    @unittest.skip(reason="MaskFormer does not have a get_input_embeddings method"      )
    def 					lowerCAmelCase__					(      self	:							Dict      ):






       '''simple docstring'''






       pass




    @unittest.skip(reason="MaskFormer is not a generative model"      )
    def 					lowerCAmelCase__					(      self	:							List[Any]      ):






       '''simple docstring'''






       pass




    @unittest.skip(reason="MaskFormer does not use token embeddings"      )
    def 					lowerCAmelCase__					(      self	:							Any      ):






       '''simple docstring'''






       pass




    @require_torch_multi_gpu
    @unittest.skip(
        reason="MaskFormer has some layers using `add_module` which doesn't work well with `nn.DataParallel`"      )
    def 					lowerCAmelCase__					(      self	:							Dict      ):






       '''simple docstring'''






       pass




    @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."      )
    def 					lowerCAmelCase__					(      self	:							int      ):






       '''simple docstring'''






       pass




    def 					lowerCAmelCase__					(      self	:							int      ):






       '''simple docstring'''






       lowercase_     ,		lowercase_						:     Optional[Any]							     =  self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
          lowercase_						:     int							     =  model_class(a      )
          lowercase_						:     List[Any]							     =  inspect.signature(model.forward      )
          # signature.parameters is an OrderedDict => so arg_names order is deterministic
          lowercase_						:     Optional[Any]							     =  [*signature.parameters.keys()]

          lowercase_						:     str							     =  ["pixel_values"]
          self.assertListEqual(arg_names[:1]	,  a      )




    @slow
    def 					lowerCAmelCase__					(      self	:							Optional[Any]      ):






       '''simple docstring'''






       for model_name in ["facebook/maskformer-swin-small-coco"]:
          lowercase_						:     str							     =  MaskFormerModel.from_pretrained(a      )
          self.assertIsNotNone(a      )




    def 					lowerCAmelCase__					(      self	:							Any      ):






       '''simple docstring'''






       lowercase_						:     Optional[Any]							     =  (self.model_tester.min_size,) * 2
       lowercase_						:     Optional[Any]							     =  {
           "pixel_values": torch.randn((2, 3, *size)	,  device=a      ),
           "mask_labels": torch.randn((2, 1_0, *size)	,  device=a      ),
           "class_labels": torch.zeros(2	,  1_0	,  device=a      ).long(),
       }

       lowercase_						:     Dict							     =  MaskFormerForInstanceSegmentation(MaskFormerConfig()      ).to(a      )
       lowercase_						:     int							     =  model(**a      )
       self.assertTrue(outputs.loss is not None      )




    def 					lowerCAmelCase__					(      self	:							Tuple      ):






       '''simple docstring'''






       lowercase_     ,		lowercase_						:     str							     =  self.model_tester.prepare_config_and_inputs_for_common()
       self.model_tester.create_and_check_maskformer_model(a	,  **a	,  output_hidden_states=a      )




    def 					lowerCAmelCase__					(      self	:							List[str]      ):






       '''simple docstring'''






       lowercase_     ,		lowercase_						:     Dict							     =  self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
          lowercase_						:     List[Any]							     =  model_class(a      ).to(a      )
          lowercase_						:     Tuple							     =  model(**a	,  output_attentions=a      )
          self.assertTrue(outputs.attentions is not None      )




    def 					lowerCAmelCase__					(      self	:							int      ):






       '''simple docstring'''






       if not self.model_tester.is_training:
          return
       # only MaskFormerForInstanceSegmentation has the loss
       lowercase_						:     List[Any]							     =  self.all_model_classes[1]
       lowercase_     ,		lowercase_     ,		lowercase_     ,		lowercase_     ,		lowercase_						:     Optional[int]							     =  self.model_tester.prepare_config_and_inputs()

       lowercase_						:     List[Any]							     =  model_class(a      )
       model.to(a      )
       model.train()

       lowercase_						:     Dict							     =  model(a	,  mask_labels=a	,  class_labels=a      ).loss
       loss.backward()





    def 					lowerCAmelCase__					(      self	:							int      ):






       '''simple docstring'''






       lowercase_						:     int							     =  self.all_model_classes[1]
       lowercase_     ,		lowercase_     ,		lowercase_     ,		lowercase_     ,		lowercase_						:     List[Any]							     =  self.model_tester.prepare_config_and_inputs()
       lowercase_						:     List[Any]							     =  True
       lowercase_						:     str							     =  True

       lowercase_						:     Optional[Any]							     =  model_class(a      )
       model.to(a      )
       model.train()

       lowercase_						:     Any							     =  model(a	,  mask_labels=a	,  class_labels=a      )

       lowercase_						:     int							     =  outputs.encoder_hidden_states[0]
       encoder_hidden_states.retain_grad()

       lowercase_						:     Any							     =  outputs.pixel_decoder_hidden_states[0]
       pixel_decoder_hidden_states.retain_grad()
       # we requires_grad=True in inputs_embeds (line 2152), the original implementation don't
       lowercase_						:     Dict							     =  outputs.transformer_decoder_hidden_states[0]
       transformer_decoder_hidden_states.retain_grad()

       lowercase_						:     List[Any]							     =  outputs.attentions[0]
       attentions.retain_grad()

       outputs.loss.backward(retain_graph=a      )

       self.assertIsNotNone(encoder_hidden_states.grad      )
       self.assertIsNotNone(pixel_decoder_hidden_states.grad      )
       self.assertIsNotNone(transformer_decoder_hidden_states.grad      )
       self.assertIsNotNone(attentions.grad      )


UpperCamelCase__			=      1e-4




def 		__SCREAMING_SNAKE_CASE       (	):


   """simple docstring"""




   lowercase_						:     List[str]							     =  Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"				)
   return image





@require_vision
@slow
class 							_UpperCAmelCase    (		unittest.TestCase      ):




    @cached_property
    def 					lowerCAmelCase__					(      self	:							List[str]      ):






       '''simple docstring'''






       return (
           MaskFormerImageProcessor.from_pretrained("facebook/maskformer-swin-small-coco"      )
           if is_vision_available()
           else None
       )




    def 					lowerCAmelCase__					(      self	:							int      ):






       '''simple docstring'''






       lowercase_						:     List[str]							     =  MaskFormerModel.from_pretrained("facebook/maskformer-swin-small-coco"      ).to(a      )
       lowercase_						:     List[str]							     =  self.default_image_processor
       lowercase_						:     Optional[int]							     =  prepare_img()
       lowercase_						:     List[Any]							     =  image_processor(a	,  return_tensors="pt"      ).to(a      )
       lowercase_						:     Tuple							     =  inputs["pixel_values"].shape
       # check size is divisible by 32
       self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0      )
       # check size
       self.assertEqual(a	,  (1, 3, 8_0_0, 1_0_8_8)      )

       with torch.no_grad():
          lowercase_						:     Optional[int]							     =  model(**a      )

       lowercase_						:     List[Any]							     =  torch.tensor(
           [[-0.0482, 0.9228, 0.4951], [-0.2547, 0.8017, 0.8527], [-0.0069, 0.3385, -0.0089]]      ).to(a      )
       self.assertTrue(
           torch.allclose(
               outputs.encoder_last_hidden_state[0, 0, :3, :3]	,  a	,  atol=a      )      )

       lowercase_						:     int							     =  torch.tensor(
           [[-0.8422, -0.8434, -0.9718], [-1.0144, -0.5565, -0.4195], [-1.0038, -0.4484, -0.1961]]      ).to(a      )
       self.assertTrue(
           torch.allclose(
               outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3]	,  a	,  atol=a      )      )

       lowercase_						:     Optional[int]							     =  torch.tensor(
           [[0.2852, -0.0159, 0.9735], [0.6254, 0.1858, 0.8529], [-0.0680, -0.4116, 1.8413]]      ).to(a      )
       self.assertTrue(
           torch.allclose(
               outputs.transformer_decoder_last_hidden_state[0, :3, :3]	,  a	,  atol=a      )      )




    def 					lowerCAmelCase__					(      self	:							Optional[int]      ):






       '''simple docstring'''






       lowercase_						:     Any							     =  (
           MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-swin-small-coco"      )
           .to(a      )
           .eval()
       )
       lowercase_						:     Dict							     =  self.default_image_processor
       lowercase_						:     List[str]							     =  prepare_img()
       lowercase_						:     int							     =  image_processor(a	,  return_tensors="pt"      ).to(a      )
       lowercase_						:     List[str]							     =  inputs["pixel_values"].shape
       # check size is divisible by 32
       self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0      )
       # check size
       self.assertEqual(a	,  (1, 3, 8_0_0, 1_0_8_8)      )

       with torch.no_grad():
          lowercase_						:     Any							     =  model(**a      )
       # masks_queries_logits
       lowercase_						:     int							     =  outputs.masks_queries_logits
       self.assertEqual(
           masks_queries_logits.shape	,  (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)	,  )
       lowercase_						:     Optional[int]							     =  [
           [-1.373_7124, -1.772_4937, -1.936_4233],
           [-1.597_7281, -1.986_7939, -2.152_3695],
           [-1.579_5398, -1.926_9832, -2.09_3942],
       ]
       lowercase_						:     int							     =  torch.tensor(a      ).to(a      )
       self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]	,  a	,  atol=a      )      )
       # class_queries_logits
       lowercase_						:     int							     =  outputs.class_queries_logits
       self.assertEqual(
           class_queries_logits.shape	,  (1, model.config.decoder_config.num_queries, model.config.num_labels + 1)      )
       lowercase_						:     str							     =  torch.tensor(
           [
               [1.6512e00, -5.2572e00, -3.3519e00],
               [3.6169e-02, -5.9025e00, -2.9313e00],
               [1.0766e-04, -7.7630e00, -5.1263e00],
           ]      ).to(a      )
       self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]	,  a	,  atol=a      )      )




    def 					lowerCAmelCase__					(      self	:							List[str]      ):






       '''simple docstring'''






       lowercase_						:     List[str]							     =  (
           MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-resnet101-coco-stuff"      )
           .to(a      )
           .eval()
       )
       lowercase_						:     Optional[Any]							     =  self.default_image_processor
       lowercase_						:     str							     =  prepare_img()
       lowercase_						:     Optional[int]							     =  image_processor(a	,  return_tensors="pt"      ).to(a      )
       lowercase_						:     int							     =  inputs["pixel_values"].shape
       # check size is divisible by 32
       self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0      )
       # check size
       self.assertEqual(a	,  (1, 3, 8_0_0, 1_0_8_8)      )

       with torch.no_grad():
          lowercase_						:     Any							     =  model(**a      )
       # masks_queries_logits
       lowercase_						:     Dict							     =  outputs.masks_queries_logits
       self.assertEqual(
           masks_queries_logits.shape	,  (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)	,  )
       lowercase_						:     List[Any]							     =  [[-0.9046, -2.6366, -4.6062], [-3.4179, -5.7890, -8.8057], [-4.9179, -7.6560, -10.7711]]
       lowercase_						:     List[str]							     =  torch.tensor(a      ).to(a      )
       self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]	,  a	,  atol=a      )      )
       # class_queries_logits
       lowercase_						:     Optional[Any]							     =  outputs.class_queries_logits
       self.assertEqual(
           class_queries_logits.shape	,  (1, model.config.decoder_config.num_queries, model.config.num_labels + 1)      )
       lowercase_						:     Union[str, Any]							     =  torch.tensor(
           [[4.7188, -3.2585, -2.8857], [6.6871, -2.9181, -1.2487], [7.2449, -2.2764, -2.1874]]      ).to(a      )
       self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]	,  a	,  atol=a      )      )





    def 					lowerCAmelCase__					(      self	:							Tuple      ):






       '''simple docstring'''






       lowercase_						:     int							     =  (
           MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-swin-small-coco"      )
           .to(a      )
           .eval()
       )
       lowercase_						:     Dict							     =  self.default_image_processor

       lowercase_						:     List[str]							     =  image_processor(
           [np.zeros((3, 8_0_0, 1_3_3_3)      ), np.zeros((3, 8_0_0, 1_3_3_3)      )]	,  segmentation_maps=[np.zeros((3_8_4, 3_8_4)      ).astype(np.floataa      ), np.zeros((3_8_4, 3_8_4)      ).astype(np.floataa      )]	,  return_tensors="pt"	,  )

       lowercase_						:     Optional[int]							     =  inputs["pixel_values"].to(a      )
       lowercase_						:     Optional[int]							     =  [el.to(a      ) for el in inputs["mask_labels"]]
       lowercase_						:     Optional[int]							     =  [el.to(a      ) for el in inputs["class_labels"]]

       with torch.no_grad():
          lowercase_						:     int							     =  model(**a      )

       self.assertTrue(outputs.loss is not None      )












'''simple docstring'''
import contextlib
import importlib
import io
import unittest

import transformers

# Try to import everything from transformers to ensure every object can be loaded.
from transformers import *  # noqa F406
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch
from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available


if is_torch_available():
 from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification

if is_tf_available():
 from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification

if is_flax_available():
 from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification


UpperCamelCase__			=      DUMMY_UNKNOWN_IDENTIFIER
# An actual model hosted on huggingface.co

UpperCamelCase__			=      'main'
# Default branch name
UpperCamelCase__			=      'f2c752cfc5c0ab6f4bdec59acea69eefbee381c2'
# One particular commit (not the top of `main`)
UpperCamelCase__			=      'aaaaaaa'
# This commit does not exist, so we should 404.

UpperCamelCase__			=      'd9e9f15bc825e4b2c9249e9578f884bbcb5e3684'
# Sha-1 of config.json on the top of `main`, for checking purposes
UpperCamelCase__			=      '4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3'




@contextlib.contextmanager
def 		__SCREAMING_SNAKE_CASE       (	):


   """simple docstring"""




   print("Welcome!"				)
   yield
   print("Bye!"				)




@contextlib.contextmanager
def 		__SCREAMING_SNAKE_CASE       (	):


   """simple docstring"""




   print("Bonjour!"				)
   yield
   print("Au revoir!"				)


class 							_UpperCAmelCase    (		unittest.TestCase      ):




    def 					lowerCAmelCase__					(      self	:							int      ):






       '''simple docstring'''






       assert transformers.__spec__ is not None
       assert importlib.util.find_spec("transformers"      ) is not None


class 							_UpperCAmelCase    (		unittest.TestCase      ):




    @unittest.mock.patch("sys.stdout"	,  new_callable=io.StringIO      )
    def 					lowerCAmelCase__					(      self	:							str	,  a	:							List[str]      ):






       '''simple docstring'''






       with ContextManagers([]      ):
          print("Transformers are awesome!"      )
       # The print statement adds a new line at the end of the output
       self.assertEqual(mock_stdout.getvalue()	,  "Transformers are awesome!\n"      )




    @unittest.mock.patch("sys.stdout"	,  new_callable=io.StringIO      )
    def 					lowerCAmelCase__					(      self	:							List[str]	,  a	:							Optional[int]      ):






       '''simple docstring'''






       with ContextManagers([context_en()]      ):
          print("Transformers are awesome!"      )
       # The output should be wrapped with an English welcome and goodbye
       self.assertEqual(mock_stdout.getvalue()	,  "Welcome!\nTransformers are awesome!\nBye!\n"      )




    @unittest.mock.patch("sys.stdout"	,  new_callable=io.StringIO      )
    def 					lowerCAmelCase__					(      self	:							Tuple	,  a	:							List[Any]      ):






       '''simple docstring'''






       with ContextManagers([context_fr(), context_en()]      ):
          print("Transformers are awesome!"      )
       # The output should be wrapped with an English and French welcome and goodbye
       self.assertEqual(mock_stdout.getvalue()	,  "Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n"      )




    @require_torch
    def 					lowerCAmelCase__					(      self	:							Tuple      ):






       '''simple docstring'''






       self.assertEqual(find_labels(a      )	,  ["labels"]      )
       self.assertEqual(find_labels(a      )	,  ["labels", "next_sentence_label"]      )
       self.assertEqual(find_labels(a      )	,  ["start_positions", "end_positions"]      )


       class 							_UpperCAmelCase    (		snake_case      ):
           pass


       self.assertEqual(find_labels(a      )	,  ["labels"]      )




    @require_tf
    def 					lowerCAmelCase__					(      self	:							int      ):






       '''simple docstring'''






       self.assertEqual(find_labels(a      )	,  ["labels"]      )
       self.assertEqual(find_labels(a      )	,  ["labels", "next_sentence_label"]      )
       self.assertEqual(find_labels(a      )	,  ["start_positions", "end_positions"]      )


       class 							_UpperCAmelCase    (		snake_case      ):
           pass


       self.assertEqual(find_labels(a      )	,  ["labels"]      )





    @require_flax
    def 					lowerCAmelCase__					(      self	:							str      ):






       '''simple docstring'''






       self.assertEqual(find_labels(a      )	,  []      )
       self.assertEqual(find_labels(a      )	,  []      )
       self.assertEqual(find_labels(a      )	,  []      )


       class 							_UpperCAmelCase    (		snake_case      ):
           pass


       self.assertEqual(find_labels(a      )	,  []      )




