
'''simple docstring'''

import os
import tempfile
import unittest

from transformers import FlaubertConfig, is_torch_available
from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
     import torch

     from transformers import (
         FlaubertForMultipleChoice,
         FlaubertForQuestionAnswering,
         FlaubertForQuestionAnsweringSimple,
         FlaubertForSequenceClassification,
         FlaubertForTokenClassification,
         FlaubertModel,
         FlaubertWithLMHeadModel,
     )
     from transformers.models.flaubert.modeling_flaubert import FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST




class    lowerCAmelCase       (     UpperCamelCase_  ):


 def __init__(    self  : List[str]			,							a__  : int			,							a__  : Optional[Any]=13			,							a__  : List[Any]=7			,							a__  : List[Any]=True			,							a__  : Optional[Any]=True			,							a__  : int=True			,							a__  : List[Any]=True			,							a__  : Union[str, Any]=True			,							a__  : Any=False			,							a__  : Any=False			,							a__  : Optional[Any]=False			,							a__  : List[str]=2			,							a__  : Tuple=99			,							a__  : List[Any]=0			,							a__  : Optional[int]=32			,							a__  : Any=5			,							a__  : str=4			,							a__  : str=0.1			,							a__  : Optional[Any]=0.1			,							a__  : str=512			,							a__  : Dict=12			,							a__  : Optional[Any]=2			,							a__  : Dict=0.02			,							a__  : Optional[int]=3			,							a__  : List[Any]=4			,							a__  : Any="last"			,							a__  : Any=None			,							a__  : Optional[int]=None			,							):
  '''simple docstring'''

  lowerCAmelCase__     :   Optional[int]     		=	parent
  lowerCAmelCase__     :   Optional[int]     		=	batch_size
  lowerCAmelCase__     :   List[Any]     		=	seq_length
  lowerCAmelCase__     :   Optional[Any]     		=	is_training
  lowerCAmelCase__     :   int     		=	use_input_lengths
  lowerCAmelCase__     :   Any     		=	use_token_type_ids
  lowerCAmelCase__     :   List[str]     		=	use_labels
  lowerCAmelCase__     :   Tuple     		=	gelu_activation
  lowerCAmelCase__     :   int     		=	sinusoidal_embeddings
  lowerCAmelCase__     :   str     		=	causal
  lowerCAmelCase__     :   str     		=	asm
  lowerCAmelCase__     :   List[str]     		=	n_langs
  lowerCAmelCase__     :   Union[str, Any]     		=	vocab_size
  lowerCAmelCase__     :   List[str]     		=	n_special
  lowerCAmelCase__     :   Dict     		=	hidden_size
  lowerCAmelCase__     :   Optional[int]     		=	num_hidden_layers
  lowerCAmelCase__     :   List[Any]     		=	num_attention_heads
  lowerCAmelCase__     :   Optional[Any]     		=	hidden_dropout_prob
  lowerCAmelCase__     :   Union[str, Any]     		=	attention_probs_dropout_prob
  lowerCAmelCase__     :   Dict     		=	max_position_embeddings
  lowerCAmelCase__     :   int     		=	type_vocab_size
  lowerCAmelCase__     :   Union[str, Any]     		=	type_sequence_label_size
  lowerCAmelCase__     :   int     		=	initializer_range
  lowerCAmelCase__     :   List[str]     		=	num_labels
  lowerCAmelCase__     :   str     		=	num_choices
  lowerCAmelCase__     :   Optional[Any]     		=	summary_type
  lowerCAmelCase__     :   List[Any]     		=	use_proj
  lowerCAmelCase__     :   Optional[int]     		=	scope


 def    _A	(    self  : Any    ):
  '''simple docstring'''

  lowerCAmelCase__     :   List[str]     		=	ids_tensor([self.batch_size, self.seq_length]			,							self.vocab_size    )
  lowerCAmelCase__     :   Tuple     		=	random_attention_mask([self.batch_size, self.seq_length]    )

  lowerCAmelCase__     :   int     		=	None
  if self.use_input_lengths:
   lowerCAmelCase__     :   Dict     		=	(
       ids_tensor([self.batch_size]			,							vocab_size=2    ) + self.seq_length - 2
   )  # small variation of seq_length

  lowerCAmelCase__     :   Any     		=	None
  if self.use_token_type_ids:
   lowerCAmelCase__     :   Any     		=	ids_tensor([self.batch_size, self.seq_length]			,							self.n_langs    )

  lowerCAmelCase__     :   str     		=	None
  lowerCAmelCase__     :   Optional[Any]     		=	None
  lowerCAmelCase__     :   str     		=	None
  if self.use_labels:
   lowerCAmelCase__     :   List[Any]     		=	ids_tensor([self.batch_size]			,							self.type_sequence_label_size    )
   lowerCAmelCase__     :   int     		=	ids_tensor([self.batch_size, self.seq_length]			,							self.num_labels    )
   lowerCAmelCase__     :   Union[str, Any]     		=	ids_tensor([self.batch_size]			,							2    ).float()
   lowerCAmelCase__     :   Optional[Any]     		=	ids_tensor([self.batch_size]			,							self.num_choices    )

  lowerCAmelCase__     :   Optional[Any]     		=	self.get_config()

  return (
      config,
      input_ids,
      token_type_ids,
      input_lengths,
      sequence_labels,
      token_labels,
      is_impossible_labels,
      choice_labels,
      input_mask,
  )


 def    _A	(    self  : List[str]    ):
  '''simple docstring'''

  return FlaubertConfig(
      vocab_size=self.vocab_size			,							n_special=self.n_special			,							emb_dim=self.hidden_size			,							n_layers=self.num_hidden_layers			,							n_heads=self.num_attention_heads			,							dropout=self.hidden_dropout_prob			,							attention_dropout=self.attention_probs_dropout_prob			,							gelu_activation=self.gelu_activation			,							sinusoidal_embeddings=self.sinusoidal_embeddings			,							asm=self.asm			,							causal=self.causal			,							n_langs=self.n_langs			,							max_position_embeddings=self.max_position_embeddings			,							initializer_range=self.initializer_range			,							summary_type=self.summary_type			,							use_proj=self.use_proj			,							)


 def    _A	(    self  : str			,							a__  : List[str]			,							a__  : Union[str, Any]			,							a__  : Optional[Any]			,							a__  : str			,							a__  : Any			,							a__  : Optional[Any]			,							a__  : Optional[int]			,							a__  : str			,							a__  : int			,							):
  '''simple docstring'''

  lowerCAmelCase__     :   Union[str, Any]     		=	FlaubertModel(config=a__    )
  model.to(a__    )
  model.eval()
  lowerCAmelCase__     :   Any     		=	model(a__			,							lengths=a__			,							langs=a__    )
  lowerCAmelCase__     :   Dict     		=	model(a__			,							langs=a__    )
  lowerCAmelCase__     :   Dict     		=	model(a__    )
  self.parent.assertEqual(result.last_hidden_state.shape			,							(self.batch_size, self.seq_length, self.hidden_size)    )


 def    _A	(    self  : Union[str, Any]			,							a__  : List[Any]			,							a__  : Union[str, Any]			,							a__  : Tuple			,							a__  : Tuple			,							a__  : Tuple			,							a__  : List[Any]			,							a__  : Any			,							a__  : int			,							a__  : Union[str, Any]			,							):
  '''simple docstring'''

  lowerCAmelCase__     :   Optional[Any]     		=	FlaubertWithLMHeadModel(a__    )
  model.to(a__    )
  model.eval()

  lowerCAmelCase__     :   int     		=	model(a__			,							token_type_ids=a__			,							labels=a__    )
  self.parent.assertEqual(result.loss.shape			,							()    )
  self.parent.assertEqual(result.logits.shape			,							(self.batch_size, self.seq_length, self.vocab_size)    )


 def    _A	(    self  : Optional[int]			,							a__  : List[str]			,							a__  : str			,							a__  : List[str]			,							a__  : int			,							a__  : int			,							a__  : str			,							a__  : Dict			,							a__  : List[str]			,							a__  : int			,							):
  '''simple docstring'''

  lowerCAmelCase__     :   int     		=	FlaubertForQuestionAnsweringSimple(a__    )
  model.to(a__    )
  model.eval()

  lowerCAmelCase__     :   Tuple     		=	model(a__    )

  lowerCAmelCase__     :   Tuple     		=	model(a__			,							start_positions=a__			,							end_positions=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)    )


 def    _A	(    self  : List[str]			,							a__  : List[str]			,							a__  : List[Any]			,							a__  : List[str]			,							a__  : Dict			,							a__  : List[Any]			,							a__  : List[str]			,							a__  : Tuple			,							a__  : Union[str, Any]			,							a__  : Optional[Any]			,							):
  '''simple docstring'''

  lowerCAmelCase__     :   Tuple     		=	FlaubertForQuestionAnswering(a__    )
  model.to(a__    )
  model.eval()

  lowerCAmelCase__     :   Any     		=	model(a__    )

  lowerCAmelCase__     :   Dict     		=	model(
      a__			,							start_positions=a__			,							end_positions=a__			,							cls_index=a__			,							is_impossible=a__			,							p_mask=a__			,							)

  lowerCAmelCase__     :   Tuple     		=	model(
      a__			,							start_positions=a__			,							end_positions=a__			,							cls_index=a__			,							is_impossible=a__			,							)

  ((lowerCAmelCase__)		,     )     :   Tuple     		=	result_with_labels.to_tuple()

  lowerCAmelCase__     :   List[str]     		=	model(a__			,							start_positions=a__			,							end_positions=a__    )

  ((lowerCAmelCase__)		,     )     :   str     		=	result_with_labels.to_tuple()

  self.parent.assertEqual(result_with_labels.loss.shape			,							()    )
  self.parent.assertEqual(result.start_top_log_probs.shape			,							(self.batch_size, model.config.start_n_top)    )
  self.parent.assertEqual(result.start_top_index.shape			,							(self.batch_size, model.config.start_n_top)    )
  self.parent.assertEqual(
      result.end_top_log_probs.shape			,							(self.batch_size, model.config.start_n_top * model.config.end_n_top)    )
  self.parent.assertEqual(
      result.end_top_index.shape			,							(self.batch_size, model.config.start_n_top * model.config.end_n_top)    )
  self.parent.assertEqual(result.cls_logits.shape			,							(self.batch_size,)    )


 def    _A	(    self  : Optional[Any]			,							a__  : int			,							a__  : Any			,							a__  : str			,							a__  : Dict			,							a__  : Dict			,							a__  : Dict			,							a__  : str			,							a__  : Optional[int]			,							a__  : Optional[Any]			,							):
  '''simple docstring'''

  lowerCAmelCase__     :   Any     		=	FlaubertForSequenceClassification(a__    )
  model.to(a__    )
  model.eval()

  lowerCAmelCase__     :   Optional[int]     		=	model(a__    )
  lowerCAmelCase__     :   Optional[int]     		=	model(a__			,							labels=a__    )

  self.parent.assertEqual(result.loss.shape			,							()    )
  self.parent.assertEqual(result.logits.shape			,							(self.batch_size, self.type_sequence_label_size)    )


 def    _A	(    self  : List[Any]			,							a__  : Optional[Any]			,							a__  : str			,							a__  : Optional[int]			,							a__  : Union[str, Any]			,							a__  : Tuple			,							a__  : Union[str, Any]			,							a__  : Optional[int]			,							a__  : Union[str, Any]			,							a__  : List[Any]			,							):
  '''simple docstring'''

  lowerCAmelCase__     :   Any     		=	self.num_labels
  lowerCAmelCase__     :   List[str]     		=	FlaubertForTokenClassification(a__    )
  model.to(a__    )
  model.eval()

  lowerCAmelCase__     :   Tuple     		=	model(a__			,							attention_mask=a__			,							labels=a__    )
  self.parent.assertEqual(result.logits.shape			,							(self.batch_size, self.seq_length, self.num_labels)    )


 def    _A	(    self  : Optional[int]			,							a__  : List[Any]			,							a__  : Tuple			,							a__  : Dict			,							a__  : Any			,							a__  : Optional[Any]			,							a__  : List[str]			,							a__  : List[Any]			,							a__  : Optional[int]			,							a__  : int			,							):
  '''simple docstring'''

  lowerCAmelCase__     :   Any     		=	self.num_choices
  lowerCAmelCase__     :   Tuple     		=	FlaubertForMultipleChoice(config=a__    )
  model.to(a__    )
  model.eval()
  lowerCAmelCase__     :   int     		=	input_ids.unsqueeze(1    ).expand(-1			,							self.num_choices			,							-1    ).contiguous()
  lowerCAmelCase__     :   Optional[int]     		=	token_type_ids.unsqueeze(1    ).expand(-1			,							self.num_choices			,							-1    ).contiguous()
  lowerCAmelCase__     :   str     		=	input_mask.unsqueeze(1    ).expand(-1			,							self.num_choices			,							-1    ).contiguous()
  lowerCAmelCase__     :   int     		=	model(
      a__			,							attention_mask=a__			,							token_type_ids=a__			,							labels=a__			,							)
  self.parent.assertEqual(result.logits.shape			,							(self.batch_size, self.num_choices)    )


 def    _A	(    self  : Any    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Optional[Any]     		=	self.prepare_config_and_inputs()
  (
      (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     
  )     :   Dict     		=	config_and_inputs
  lowerCAmelCase__     :   Tuple     		=	{
      "input_ids": input_ids,
      "token_type_ids": token_type_ids,
      "lengths": input_lengths,
      "attention_mask": input_mask,
  }
  return config, inputs_dict




@require_torch
class    lowerCAmelCase       (     UpperCamelCase_    ,  UpperCamelCase_    ,  unittest.TestCase  ):
 A_				:				Dict	=			(
     (
         FlaubertModel,
         FlaubertWithLMHeadModel,
         FlaubertForQuestionAnswering,
         FlaubertForQuestionAnsweringSimple,
         FlaubertForSequenceClassification,
         FlaubertForTokenClassification,
         FlaubertForMultipleChoice,
     )
     if is_torch_available()
     else ()
 )
 A_				:				Optional[int]	=			(
     {
         """feature-extraction""": FlaubertModel,
         """fill-mask""": FlaubertWithLMHeadModel,
         """question-answering""": FlaubertForQuestionAnsweringSimple,
         """text-classification""": FlaubertForSequenceClassification,
         """token-classification""": FlaubertForTokenClassification,
         """zero-shot""": FlaubertForSequenceClassification,
     }
     if is_torch_available()
     else {}
 )


 def    _A	(    self  : int			,							a__  : Dict			,							a__  : List[str]			,							a__  : List[str]			,							a__  : Optional[int]			,							a__  : Union[str, Any]    ):
  '''simple docstring'''

  if (
      pipeline_test_casse_name == "QAPipelineTests"
      and tokenizer_name is not None
      and not tokenizer_name.endswith("Fast"    )
  ):
   # `QAPipelineTests` fails for a few models when the slower tokenizer are used.
   # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework)
   # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer
   return True

  return False


 def    _A	(    self  : List[str]			,							a__  : Dict			,							a__  : Any			,							a__  : Optional[Any]=False    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Any     		=	super()._prepare_for_class(a__			,							a__			,							return_labels=a__    )

  if return_labels:
   if model_class.__name__ == "FlaubertForQuestionAnswering":
    lowerCAmelCase__     :   List[str]     		=	torch.zeros(
        self.model_tester.batch_size			,							dtype=torch.long			,							device=a__    )
    lowerCAmelCase__     :   Tuple     		=	torch.zeros(
        self.model_tester.batch_size			,							dtype=torch.long			,							device=a__    )

  return inputs_dict


 def    _A	(    self  : Tuple    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Tuple     		=	FlaubertModelTester(self    )
  lowerCAmelCase__     :   Optional[Any]     		=	ConfigTester(self			,							config_class=a__			,							emb_dim=37    )


 def    _A	(    self  : Union[str, Any]    ):
  '''simple docstring'''

  self.config_tester.run_common_tests()


 def    _A	(    self  : Any    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Union[str, Any]     		=	self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_flaubert_model(*a__    )


 def    _A	(    self  : List[Any]    ):
  '''simple docstring'''

  lowerCAmelCase__     :   List[str]     		=	self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_flaubert_lm_head(*a__    )


 def    _A	(    self  : Tuple    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Any     		=	self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_flaubert_simple_qa(*a__    )


 def    _A	(    self  : str    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Dict     		=	self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_flaubert_qa(*a__    )


 def    _A	(    self  : Optional[int]    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Any     		=	self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_flaubert_sequence_classif(*a__    )


 def    _A	(    self  : Tuple    ):
  '''simple docstring'''

  lowerCAmelCase__     :   List[str]     		=	self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_flaubert_token_classif(*a__    )


 def    _A	(    self  : List[str]    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Optional[Any]     		=	self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_flaubert_multiple_choice(*a__    )


 @slow
 def    _A	(    self  : Any    ):
  '''simple docstring'''

  for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
   lowerCAmelCase__     :   int     		=	FlaubertModel.from_pretrained(a__    )
   self.assertIsNotNone(a__    )


 @slow
 @require_torch_gpu
 def    _A	(    self  : Tuple    ):
  '''simple docstring'''

  lowerCAmelCase__		,     lowerCAmelCase__     :   List[str]     		=	self.model_tester.prepare_config_and_inputs_for_common()
  for model_class in self.all_model_classes:
   # FlauBertForMultipleChoice behaves incorrectly in JIT environments.
   if model_class == FlaubertForMultipleChoice:
    return

   lowerCAmelCase__     :   Tuple     		=	True
   lowerCAmelCase__     :   List[Any]     		=	model_class(config=a__    )

   lowerCAmelCase__     :   Any     		=	self._prepare_for_class(a__			,							a__    )
   lowerCAmelCase__     :   Any     		=	torch.jit.trace(
       a__			,							(inputs_dict["input_ids"].to("cpu"    ), inputs_dict["attention_mask"].to("cpu"    ))    )

   with tempfile.TemporaryDirectory() as tmp:
    torch.jit.save(a__			,							os.path.join(a__			,							"traced_model.pt"    )    )
    lowerCAmelCase__     :   Optional[Any]     		=	torch.jit.load(os.path.join(a__			,							"traced_model.pt"    )			,							map_location=a__    )
    loaded(inputs_dict["input_ids"].to(a__    )			,							inputs_dict["attention_mask"].to(a__    )    )




@require_torch
class    lowerCAmelCase       (     unittest.TestCase  ):


 @slow
 def    _A	(    self  : int    ):
  '''simple docstring'''

  lowerCAmelCase__     :   int     		=	FlaubertModel.from_pretrained("flaubert/flaubert_base_cased"    )
  lowerCAmelCase__     :   int     		=	torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]]    )
  with torch.no_grad():
   lowerCAmelCase__     :   Any     		=	model(a__    )[0]
  lowerCAmelCase__     :   Optional[int]     		=	torch.Size((1, 11, 768)    )
  self.assertEqual(output.shape			,							a__    )
  lowerCAmelCase__     :   Union[str, Any]     		=	torch.tensor(
      [[[-2.6251, -1.4298, -0.0227], [-2.8510, -1.6387, 0.2258], [-2.8114, -1.1832, -0.3066]]]    )

  self.assertTrue(torch.allclose(output[:, :3, :3]			,							a__			,							atol=1e-4    )    )







'''simple docstring'''

from cva import destroyAllWindows, imread, imshow, waitKey


def        UpperCAmelCase_ (  lowerCamelCase_			):







 """simple docstring"""


 lowerCAmelCase__		,     lowerCAmelCase__     :   Tuple     		=	img.shape[0], img.shape[1]

 # converting each pixel's color to its negative
 for i in range(lowerCamelCase_			):
  for j in range(lowerCamelCase_			):
   lowerCAmelCase__     :   Optional[int]     		=	[2_5_5, 2_5_5, 2_5_5] - img[i][j]

 return img


if __name__ == "__main__":
     # read original image
     snake_case									=    imread("""image_data/lena.jpg""", 1)

     # convert to its negative
     snake_case									=    convert_to_negative(img)

     # show result image
     imshow("""negative of original image""", img)
     waitKey(0)
     destroyAllWindows()





