
'''simple docstring'''

from __future__ import annotations

import collections
import tempfile
import unittest

import numpy as np

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

from ...test_modeling_tf_common import floats_tensor, ids_tensor, random_attention_mask
from ..bert.test_modeling_tf_bert import TFBertModelTester
from ..clip.test_modeling_tf_clip import TFCLIPVisionModelTester
from ..deit.test_modeling_tf_deit import TFDeiTModelTester
from ..roberta.test_modeling_tf_roberta import TFRobertaModelTester
from ..vit.test_modeling_tf_vit import TFViTModelTester


if is_tf_available():
     from transformers import (
         TFBertModel,
         TFCLIPVisionModel,
         TFDeiTModel,
         TFRobertaModel,
         TFVisionTextDualEncoderModel,
         TFViTModel,
         VisionTextDualEncoderConfig,
     )

if is_vision_available():
     from PIL import Image

     from transformers import VisionTextDualEncoderProcessor


def        UpperCAmelCase_ (  lowerCamelCase_			):







 """simple docstring"""


 if isinstance(lowerCamelCase_      ,			collections.abc.Iterable			):
  return x
 return (x, x)




@require_tf
class    lowerCAmelCase       :


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

  pass


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

  pass


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

  pass


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

  lowerCAmelCase__     :   List[Any]     		=	VisionTextDualEncoderConfig.from_vision_text_configs(a__			,							a__    )

  lowerCAmelCase__     :   Optional[int]     		=	TFVisionTextDualEncoderModel(a__    )

  lowerCAmelCase__     :   List[Any]     		=	model(input_ids=a__			,							pixel_values=a__			,							attention_mask=a__    )

  self.assertEqual(output["text_embeds"].shape			,							(input_ids.shape[0], config.projection_dim)    )
  self.assertEqual(output["image_embeds"].shape			,							(pixel_values.shape[0], config.projection_dim)    )


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

  lowerCAmelCase__		,     lowerCAmelCase__     :   List[str]     		=	self.get_vision_text_model(a__			,							a__    )
  lowerCAmelCase__     :   Dict     		=	TFVisionTextDualEncoderModel(vision_model=a__			,							text_model=a__    )

  lowerCAmelCase__     :   Any     		=	model(input_ids=a__			,							pixel_values=a__			,							attention_mask=a__    )

  self.assertEqual(output["text_embeds"].shape			,							(input_ids.shape[0], model.config.projection_dim)    )
  self.assertEqual(output["image_embeds"].shape			,							(pixel_values.shape[0], model.config.projection_dim)    )


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

  lowerCAmelCase__		,     lowerCAmelCase__     :   str     		=	self.get_vision_text_model(a__			,							a__    )
  lowerCAmelCase__     :   List[str]     		=	{"vision_model": vision_model, "text_model": text_model}
  lowerCAmelCase__     :   Tuple     		=	TFVisionTextDualEncoderModel.from_vision_text_pretrained(**a__    )

  lowerCAmelCase__     :   Union[str, Any]     		=	model(input_ids=a__			,							pixel_values=a__			,							attention_mask=a__    )

  self.assertEqual(output["text_embeds"].shape			,							(input_ids.shape[0], model.config.projection_dim)    )
  self.assertEqual(output["image_embeds"].shape			,							(pixel_values.shape[0], model.config.projection_dim)    )


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

  lowerCAmelCase__		,     lowerCAmelCase__     :   int     		=	self.get_vision_text_model(a__			,							a__    )
  lowerCAmelCase__     :   Tuple     		=	TFVisionTextDualEncoderModel(vision_model=a__			,							text_model=a__    )

  lowerCAmelCase__     :   Optional[Any]     		=	model(input_ids=a__			,							pixel_values=a__			,							attention_mask=a__    )
  lowerCAmelCase__     :   str     		=	output[0].numpy()

  with tempfile.TemporaryDirectory() as tmpdirname:
   model.save_pretrained(a__    )
   lowerCAmelCase__     :   Optional[Any]     		=	TFVisionTextDualEncoderModel.from_pretrained(a__    )

   lowerCAmelCase__     :   Union[str, Any]     		=	model(input_ids=a__			,							pixel_values=a__			,							attention_mask=a__    )
   lowerCAmelCase__     :   Optional[int]     		=	after_output[0].numpy()
   lowerCAmelCase__     :   Any     		=	np.amax(np.abs(out_a - out_a    )    )
   self.assertLessEqual(a__			,							1e-5    )


 def    _A	(    self  : Tuple			,							a__  : Dict			,							a__  : Tuple			,							a__  : Dict			,							a__  : str			,							a__  : Union[str, Any]=None			,							**a__  : int    ):
  '''simple docstring'''

  lowerCAmelCase__		,     lowerCAmelCase__     :   Dict     		=	self.get_vision_text_model(a__			,							a__    )
  lowerCAmelCase__     :   Dict     		=	TFVisionTextDualEncoderModel(vision_model=a__			,							text_model=a__    )

  lowerCAmelCase__     :   Any     		=	model(
      input_ids=a__			,							pixel_values=a__			,							attention_mask=a__			,							output_attentions=a__    )

  lowerCAmelCase__     :   Any     		=	output.vision_model_output.attentions
  self.assertEqual(len(a__    )			,							vision_config.num_hidden_layers    )

  # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token)
  lowerCAmelCase__     :   List[str]     		=	to_atuple(vision_model.config.image_size    )
  lowerCAmelCase__     :   Dict     		=	to_atuple(vision_model.config.patch_size    )
  lowerCAmelCase__     :   str     		=	(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
  lowerCAmelCase__     :   int     		=	num_patches + 1
  self.assertEqual(vision_attentions[0].shape[-3:]			,							(vision_config.num_attention_heads, seq_len, seq_len)    )

  lowerCAmelCase__     :   Optional[int]     		=	output.text_model_output.attentions
  self.assertEqual(len(a__    )			,							text_config.num_hidden_layers    )

  self.assertEqual(
      text_attentions[0].shape[-3:]			,							(text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1])			,							)


 def    _A	(    self  : Optional[int]			,							a__  : np.ndarray			,							a__  : np.ndarray			,							a__  : float    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Optional[Any]     		=	np.abs((a - b)    ).max()
  self.assertLessEqual(a__			,							a__			,							F'''Difference between torch and flax is {diff} (>= {tol}).'''    )


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

  lowerCAmelCase__     :   str     		=	self.prepare_config_and_inputs()
  self.check_vision_text_dual_encoder_model(**a__    )


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

  lowerCAmelCase__     :   Optional[int]     		=	self.prepare_config_and_inputs()
  self.check_model_from_pretrained_configs(**a__    )


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

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


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

  lowerCAmelCase__     :   Any     		=	self.prepare_config_and_inputs()
  self.check_save_load(**a__    )


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

  lowerCAmelCase__     :   Tuple     		=	self.prepare_config_and_inputs()
  self.check_vision_text_output_attention(**a__    )


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

  lowerCAmelCase__		,     lowerCAmelCase__     :   Union[str, Any]     		=	self.get_pretrained_model_and_inputs()

  lowerCAmelCase__     :   List[str]     		=	model_a(**a__    )
  lowerCAmelCase__     :   Optional[Any]     		=	outputs[0].numpy()

  with tempfile.TemporaryDirectory() as tmp_dirname:
   model_a.save_pretrained(a__    )
   lowerCAmelCase__     :   Dict     		=	TFVisionTextDualEncoderModel.from_pretrained(a__    )

   lowerCAmelCase__     :   Optional[Any]     		=	model_a(**a__    )
   lowerCAmelCase__     :   Union[str, Any]     		=	after_outputs[0].numpy()
   lowerCAmelCase__     :   Optional[Any]     		=	np.amax(np.abs(out_a - out_a    )    )
   self.assertLessEqual(a__			,							1e-5    )




@require_tf
class    lowerCAmelCase       (     UpperCamelCase_    ,  unittest.TestCase  ):


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

  lowerCAmelCase__     :   Dict     		=	TFVisionTextDualEncoderModel.from_vision_text_pretrained(
      "hf-internal-testing/tiny-random-vit"			,							"hf-internal-testing/tiny-random-bert"    )
  lowerCAmelCase__     :   int     		=	13
  lowerCAmelCase__     :   Union[str, Any]     		=	floats_tensor(
      [
          batch_size,
          model.vision_model.config.num_channels,
          model.vision_model.config.image_size,
          model.vision_model.config.image_size,
      ]    )
  lowerCAmelCase__     :   Tuple     		=	ids_tensor([batch_size, 4]			,							model.text_model.config.vocab_size    )
  lowerCAmelCase__     :   Union[str, Any]     		=	random_attention_mask([batch_size, 4]    )
  lowerCAmelCase__     :   Tuple     		=	{"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask}

  return model, inputs


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

  lowerCAmelCase__     :   Any     		=	TFViTModel(a__			,							name="vision_model"    )
  lowerCAmelCase__     :   Optional[int]     		=	TFBertModel(a__			,							name="text_model"    )
  return vision_model, text_model


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

  lowerCAmelCase__     :   str     		=	TFViTModelTester(self    )
  lowerCAmelCase__     :   List[Any]     		=	TFBertModelTester(self    )
  lowerCAmelCase__     :   Union[str, Any]     		=	vit_model_tester.prepare_config_and_inputs()
  lowerCAmelCase__     :   Optional[Any]     		=	bert_model_tester.prepare_config_and_inputs()

  lowerCAmelCase__		,     lowerCAmelCase__		,     lowerCAmelCase__     :   str     		=	vision_config_and_inputs

  (
      (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     
  )     :   int     		=	text_config_and_inputs

  return {
      "text_config": text_config,
      "vision_config": vision_config,
      "pixel_values": pixel_values,
      "attention_mask": input_mask,
      "input_ids": input_ids,
      "text_token_type_ids": token_type_ids,
      "text_sequence_labels": sequence_labels,
      "text_token_labels": token_labels,
      "text_choice_labels": choice_labels,
  }




@require_tf
class    lowerCAmelCase       (     UpperCamelCase_    ,  unittest.TestCase  ):


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

  lowerCAmelCase__     :   Optional[Any]     		=	TFVisionTextDualEncoderModel.from_vision_text_pretrained(
      "Rocketknight1/tiny-random-deit-tf"			,							"hf-internal-testing/tiny-random-roberta"    )
  lowerCAmelCase__     :   str     		=	13
  lowerCAmelCase__     :   Optional[int]     		=	floats_tensor(
      [
          batch_size,
          model.vision_model.config.num_channels,
          model.vision_model.config.image_size,
          model.vision_model.config.image_size,
      ]    )
  lowerCAmelCase__     :   int     		=	ids_tensor([batch_size, 4]			,							model.text_model.config.vocab_size    )
  lowerCAmelCase__     :   Tuple     		=	random_attention_mask([batch_size, 4]    )
  lowerCAmelCase__     :   int     		=	{"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask}

  return model, inputs


 def    _A	(    self  : List[str]			,							a__  : List[Any]			,							a__  : List[str]			,							a__  : str			,							a__  : Union[str, Any]			,							a__  : List[Any]=None			,							**a__  : List[str]    ):
  '''simple docstring'''

  lowerCAmelCase__		,     lowerCAmelCase__     :   Optional[int]     		=	self.get_vision_text_model(a__			,							a__    )
  lowerCAmelCase__     :   int     		=	TFVisionTextDualEncoderModel(vision_model=a__			,							text_model=a__    )

  lowerCAmelCase__     :   Optional[Any]     		=	model(
      input_ids=a__			,							pixel_values=a__			,							attention_mask=a__			,							output_attentions=a__    )

  lowerCAmelCase__     :   Tuple     		=	output.vision_model_output.attentions
  self.assertEqual(len(a__    )			,							vision_config.num_hidden_layers    )

  # in DEiT, the seq_len equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens)
  lowerCAmelCase__     :   Dict     		=	to_atuple(vision_model.config.image_size    )
  lowerCAmelCase__     :   int     		=	to_atuple(vision_model.config.patch_size    )
  lowerCAmelCase__     :   Any     		=	(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
  lowerCAmelCase__     :   str     		=	num_patches + 2
  self.assertEqual(vision_attentions[0].shape[-3:]			,							(vision_config.num_attention_heads, seq_len, seq_len)    )

  lowerCAmelCase__     :   int     		=	output.text_model_output.attentions
  self.assertEqual(len(a__    )			,							text_config.num_hidden_layers    )

  self.assertEqual(
      text_attentions[0].shape[-3:]			,							(text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1])			,							)


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

  lowerCAmelCase__     :   Any     		=	TFDeiTModel(a__			,							name="vision_model"    )
  lowerCAmelCase__     :   Tuple     		=	TFRobertaModel(a__			,							name="text_model"    )
  return vision_model, text_model


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

  lowerCAmelCase__     :   Optional[Any]     		=	TFDeiTModelTester(self    )
  lowerCAmelCase__     :   Tuple     		=	TFRobertaModelTester(self    )
  lowerCAmelCase__     :   Union[str, Any]     		=	vit_model_tester.prepare_config_and_inputs()
  lowerCAmelCase__     :   Union[str, Any]     		=	bert_model_tester.prepare_config_and_inputs()

  lowerCAmelCase__		,     lowerCAmelCase__		,     lowerCAmelCase__     :   Dict     		=	vision_config_and_inputs

  (
      (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     
  )     :   Any     		=	text_config_and_inputs

  return {
      "text_config": text_config,
      "vision_config": vision_config,
      "pixel_values": pixel_values,
      "attention_mask": input_mask,
      "input_ids": input_ids,
      "text_token_type_ids": token_type_ids,
      "text_sequence_labels": sequence_labels,
      "text_token_labels": token_labels,
      "text_choice_labels": choice_labels,
  }




@require_tf
class    lowerCAmelCase       (     UpperCamelCase_    ,  unittest.TestCase  ):


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

  lowerCAmelCase__     :   Optional[Any]     		=	TFVisionTextDualEncoderModel.from_vision_text_pretrained(
      "Rocketknight1/tiny-random-clip-tf"			,							"hf-internal-testing/tiny-random-bert"    )
  lowerCAmelCase__     :   Optional[Any]     		=	13
  lowerCAmelCase__     :   Union[str, Any]     		=	floats_tensor(
      [
          batch_size,
          model.vision_model.config.num_channels,
          model.vision_model.config.image_size,
          model.vision_model.config.image_size,
      ]    )
  lowerCAmelCase__     :   Dict     		=	ids_tensor([batch_size, 4]			,							model.text_model.config.vocab_size    )
  lowerCAmelCase__     :   Union[str, Any]     		=	random_attention_mask([batch_size, 4]    )
  lowerCAmelCase__     :   int     		=	{"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask}

  return model, inputs


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

  lowerCAmelCase__     :   int     		=	TFCLIPVisionModel(a__			,							name="vision_model"    )
  lowerCAmelCase__     :   Tuple     		=	TFBertModel(a__			,							name="text_model"    )
  return vision_model, text_model


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

  lowerCAmelCase__     :   List[Any]     		=	TFCLIPVisionModelTester(self    )
  lowerCAmelCase__     :   str     		=	TFBertModelTester(self    )
  lowerCAmelCase__     :   Optional[Any]     		=	clip_model_tester.prepare_config_and_inputs()
  lowerCAmelCase__     :   List[str]     		=	bert_model_tester.prepare_config_and_inputs()

  lowerCAmelCase__		,     lowerCAmelCase__     :   List[str]     		=	vision_config_and_inputs

  (
      (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     
  )     :   Optional[int]     		=	text_config_and_inputs

  return {
      "text_config": text_config,
      "vision_config": vision_config,
      "pixel_values": pixel_values,
      "attention_mask": input_mask,
      "input_ids": input_ids,
      "text_token_type_ids": token_type_ids,
      "text_sequence_labels": sequence_labels,
      "text_token_labels": token_labels,
      "text_choice_labels": choice_labels,
  }




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


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

  lowerCAmelCase__     :   Tuple     		=	TFVisionTextDualEncoderModel.from_pretrained(
      "clip-italian/clip-italian"			,							logit_scale_init_value=1.0			,							from_pt=a__    )
  lowerCAmelCase__     :   int     		=	VisionTextDualEncoderProcessor.from_pretrained("clip-italian/clip-italian"    )

  lowerCAmelCase__     :   Optional[int]     		=	Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"    )
  lowerCAmelCase__     :   Union[str, Any]     		=	processor(
      text=["una foto di un gatto", "una foto di un cane"]			,							images=a__			,							padding=a__			,							return_tensors="np"    )

  lowerCAmelCase__     :   List[Any]     		=	model(**a__    )

  # verify the logits
  self.assertEqual(outputs.logits_per_image.shape			,							(inputs.pixel_values.shape[0], inputs.input_ids.shape[0])    )
  self.assertEqual(
      outputs.logits_per_text.shape			,							(inputs.input_ids.shape[0], inputs.pixel_values.shape[0])			,							)

  lowerCAmelCase__     :   int     		=	np.array([[1.2284727, 0.3104122]]    )

  self.assertTrue(np.allclose(outputs.logits_per_image.numpy()			,							a__			,							atol=1e-3    )    )







'''simple docstring'''

import sys
import webbrowser

import requests
from bsa import BeautifulSoup
from fake_useragent import UserAgent

if __name__ == "__main__":
     print("""Googling.....""")
     snake_case									=    """https://www.google.com/search?q=""" + """ """.join(sys.argv[1:])
     snake_case									=    requests.get(url, headers={"""UserAgent""": UserAgent().random})
     # res.raise_for_status()
     with open("""project1a.html""", """wb""") as out_file:  # only for knowing the class
          for data in res.iter_content(1_00_00):
               out_file.write(data)
     snake_case									=    BeautifulSoup(res.text, """html.parser""")
     snake_case									=    list(soup.select(""".eZt8xd"""))[:5]

     print(len(links))
     for link in links:
          if link.text == "Maps":
               webbrowser.open(link.get("""href"""))
          else:
               webbrowser.open(f'https://google.com{link.get("href")}')





