





import collections
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import (
    is_pt_flax_cross_test,
    require_flax,
    require_torch,
    require_vision,
    slow,
    torch_device,
)
from transformers.utils import is_flax_available, is_torch_available, is_vision_available

from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask
from ..bert.test_modeling_flax_bert import FlaxBertModelTester
from ..clip.test_modeling_flax_clip import FlaxCLIPVisionModelTester
from ..vit.test_modeling_flax_vit import FlaxViTModelTester


if is_flax_available():
    from transformers import (
        FlaxBertModel,
        FlaxCLIPVisionModel,
        FlaxVisionTextDualEncoderModel,
        FlaxViTModel,
        VisionTextDualEncoderConfig,
        VisionTextDualEncoderProcessor,
    )
    from transformers.modeling_flax_pytorch_utils import (
        convert_pytorch_state_dict_to_flax,
        load_flax_weights_in_pytorch_model,
    )


if is_torch_available():
    import torch

    from transformers import VisionTextDualEncoderModel

if is_vision_available():
    from PIL import Image



def A_     (		A__    )  ->		Optional[int]:
       if isinstance(A__		,				collections.abc.Iterable    ):
              return x
       return (x, x)





@require_flax
class 			A__   :




   """simple docstring"""



   def 							__lowercase		( self ,  lowercase ,  lowercase)      ->						Any:







          '''simple docstring'''

          pass

   def 							__lowercase		( self)      ->						Union[str, Any]:







          '''simple docstring'''

          pass

   def 							__lowercase		( self)      ->						List[str]:







          '''simple docstring'''

          pass

   def 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase)      ->						Optional[Any]:







          '''simple docstring'''

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

   def 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase=None ,  **lowercase)      ->						int:







          '''simple docstring'''

          a__						:     Tuple			=    VisionTextDualEncoderConfig.from_vision_text_configs(lowercase ,  lowercase)

          a__						:     Optional[int]			=    FlaxVisionTextDualEncoderModel(lowercase)

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

          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 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase=None ,  **lowercase)      ->						Tuple:







          '''simple docstring'''

          a__			,							a__						:     int			=    self.get_vision_text_model(lowercase ,  lowercase)
          a__						:     Optional[Any]			=    {'vision_model': vision_model, 'text_model': text_model}
          a__						:     List[Any]			=    FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**lowercase)

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

          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 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase=None ,  **lowercase)      ->						Tuple:







          '''simple docstring'''

          a__			,							a__						:     Dict			=    self.get_vision_text_model(lowercase ,  lowercase)
          a__						:     Optional[Any]			=    {'vision_model': vision_model, 'text_model': text_model}
          a__						:     Dict			=    FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**lowercase)

          a__						:     Any			=    model(input_ids=lowercase ,  pixel_values=lowercase ,  attention_mask=lowercase)
          a__						:     str			=    output[0]

          with tempfile.TemporaryDirectory() as tmpdirname:
                 model.save_pretrained(lowercase)
                 a__						:     str			=    FlaxVisionTextDualEncoderModel.from_pretrained(lowercase)

                 a__						:     Tuple			=    model(input_ids=lowercase ,  pixel_values=lowercase ,  attention_mask=lowercase)
                 a__						:     List[Any]			=    after_output[0]
                 a__						:     Tuple			=    np.amax(np.abs(out_a - out_a))
                 self.assertLessEqual(lowercase ,  1e-3)

   def 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase=None ,  **lowercase)      ->						Optional[Any]:







          '''simple docstring'''

          a__			,							a__						:     int			=    self.get_vision_text_model(lowercase ,  lowercase)
          a__						:     Optional[int]			=    {'vision_model': vision_model, 'text_model': text_model}
          a__						:     Dict			=    FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**lowercase)

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

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

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

          a__						:     Optional[int]			=    output.text_model_output.attentions
          self.assertEqual(len(lowercase) ,  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 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase)      ->						Optional[Any]:







          '''simple docstring'''

          pt_model.to(lowercase)
          pt_model.eval()

          # prepare inputs
          a__						:     Optional[int]			=    inputs_dict
          a__						:     Any			=    {k: torch.tensor(v.tolist()) for k, v in flax_inputs.items()}

          with torch.no_grad():
                 a__						:     Union[str, Any]			=    pt_model(**lowercase).to_tuple()

          a__						:     Tuple			=    fx_model(**lowercase).to_tuple()
          self.assertEqual(len(lowercase) ,  len(lowercase) ,  'Output lengths differ between Flax and PyTorch')
          for fx_output, pt_output in zip(fx_outputs[:4] ,  pt_outputs[:4]):
                 self.assert_almost_equals(lowercase ,  pt_output.numpy() ,  4e-2)

          # PT -> Flax
          with tempfile.TemporaryDirectory() as tmpdirname:
                 pt_model.save_pretrained(lowercase)
                 a__						:     Tuple			=    FlaxVisionTextDualEncoderModel.from_pretrained(lowercase ,  from_pt=lowercase)

          a__						:     Optional[int]			=    fx_model_loaded(**lowercase).to_tuple()
          self.assertEqual(len(lowercase) ,  len(lowercase) ,  'Output lengths differ between Flax and PyTorch')
          for fx_output_loaded, pt_output in zip(fx_outputs_loaded[:4] ,  pt_outputs[:4]):
                 self.assert_almost_equals(lowercase ,  pt_output.numpy() ,  4e-2)

          # Flax -> PT
          with tempfile.TemporaryDirectory() as tmpdirname:
                 fx_model.save_pretrained(lowercase)
                 a__						:     Optional[Any]			=    VisionTextDualEncoderModel.from_pretrained(lowercase ,  from_flax=lowercase)

          pt_model_loaded.to(lowercase)
          pt_model_loaded.eval()

          with torch.no_grad():
                 a__						:     Dict			=    pt_model_loaded(**lowercase).to_tuple()

          self.assertEqual(len(lowercase) ,  len(lowercase) ,  'Output lengths differ between Flax and PyTorch')
          for fx_output, pt_output_loaded in zip(fx_outputs[:4] ,  pt_outputs_loaded[:4]):
                 self.assert_almost_equals(lowercase ,  pt_output_loaded.numpy() ,  4e-2)

   def 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase)      ->						Optional[int]:







          '''simple docstring'''

          a__						:     Optional[Any]			=    VisionTextDualEncoderConfig.from_vision_text_configs(lowercase ,  lowercase)

          a__						:     Union[str, Any]			=    VisionTextDualEncoderModel(lowercase)
          a__						:     Any			=    FlaxVisionTextDualEncoderModel(lowercase)

          a__						:     Optional[Any]			=    convert_pytorch_state_dict_to_flax(pt_model.state_dict() ,  lowercase)
          a__						:     Any			=    fx_state

          self.check_pt_flax_equivalence(lowercase ,  lowercase ,  lowercase)

   def 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase)      ->						List[str]:







          '''simple docstring'''

          a__						:     Any			=    VisionTextDualEncoderConfig.from_vision_text_configs(lowercase ,  lowercase)

          a__						:     Optional[int]			=    VisionTextDualEncoderModel(lowercase)
          a__						:     Optional[int]			=    FlaxVisionTextDualEncoderModel(lowercase)

          a__						:     Dict			=    load_flax_weights_in_pytorch_model(lowercase ,  fx_model.params)

          self.check_pt_flax_equivalence(lowercase ,  lowercase ,  lowercase)

   def 							__lowercase		( self)      ->						Optional[int]:







          '''simple docstring'''

          a__						:     int			=    self.prepare_config_and_inputs()
          self.check_model_from_pretrained_configs(**lowercase)

   def 							__lowercase		( self)      ->						Dict:







          '''simple docstring'''

          a__						:     Any			=    self.prepare_config_and_inputs()
          self.check_vision_text_dual_encoder_from_pretrained(**lowercase)

   def 							__lowercase		( self)      ->						Optional[Any]:







          '''simple docstring'''

          a__						:     Union[str, Any]			=    self.prepare_config_and_inputs()
          self.check_save_load(**lowercase)

   def 							__lowercase		( self)      ->						Optional[Any]:







          '''simple docstring'''

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

   @is_pt_flax_cross_test
   def 							__lowercase		( self)      ->						Tuple:







          '''simple docstring'''

          a__						:     Optional[Any]			=    self.prepare_config_and_inputs()
          a__						:     Optional[Any]			=    config_inputs_dict.pop('vision_config')
          a__						:     Optional[Any]			=    config_inputs_dict.pop('text_config')

          a__						:     Optional[int]			=    config_inputs_dict

          self.check_equivalence_pt_to_flax(lowercase ,  lowercase ,  lowercase)
          self.check_equivalence_flax_to_pt(lowercase ,  lowercase ,  lowercase)

   @slow
   def 							__lowercase		( self)      ->						List[str]:







          '''simple docstring'''

          a__			,							a__						:     str			=    self.get_pretrained_model_and_inputs()

          a__						:     str			=    model_a(**lowercase)
          a__						:     Optional[Any]			=    outputs[0]

          with tempfile.TemporaryDirectory() as tmp_dirname:
                 model_a.save_pretrained(lowercase)
                 a__						:     List[str]			=    FlaxVisionTextDualEncoderModel.from_pretrained(lowercase)

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





@require_flax
class 			A__   (							__UpperCAmelCase			,  unittest.TestCase     ):




   """simple docstring"""



   def 							__lowercase		( self)      ->						Any:







          '''simple docstring'''

          a__						:     int			=    FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
              'hf-internal-testing/tiny-random-vit' ,  'hf-internal-testing/tiny-bert' ,  vision_from_pt=lowercase ,  text_from_pt=lowercase ,  )
          a__						:     Optional[Any]			=    13
          a__						:     List[str]			=    floats_tensor(
              [
                  batch_size,
                  model.config.vision_config.num_channels,
                  model.config.vision_config.image_size,
                  model.config.vision_config.image_size,
              ])
          a__						:     List[str]			=    ids_tensor([batch_size, 4] ,  model.config.text_config.vocab_size)
          a__						:     List[Any]			=    random_attention_mask([batch_size, 4])
          a__						:     Optional[int]			=    {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

          return model, inputs

   def 							__lowercase		( self ,  lowercase ,  lowercase)      ->						Any:







          '''simple docstring'''

          a__						:     int			=    FlaxViTModel(lowercase)
          a__						:     Optional[int]			=    FlaxBertModel(lowercase)
          return vision_model, text_model

   def 							__lowercase		( self)      ->						Any:







          '''simple docstring'''

          a__						:     Dict			=    FlaxViTModelTester(self)
          a__						:     Dict			=    FlaxBertModelTester(self)
          a__						:     int			=    vit_model_tester.prepare_config_and_inputs()
          a__						:     List[Any]			=    bert_model_tester.prepare_config_and_inputs()

          a__			,							a__						:     Tuple			=    vision_config_and_inputs

          a__			,							a__			,							a__			,							a__						:     str			=    text_config_and_inputs

          # make sure that cross attention layers are added
          return {
              "text_config": text_config,
              "vision_config": vision_config,
              "pixel_values": pixel_values,
              "attention_mask": attention_mask,
              "input_ids": input_ids,
              "token_type_ids": token_type_ids,
          }





@require_torch
class 			A__   (							__UpperCAmelCase			,  unittest.TestCase     ):




   """simple docstring"""



   def 							__lowercase		( self)      ->						Tuple:







          '''simple docstring'''

          a__						:     Any			=    FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
              'hf-internal-testing/tiny-random-clip' ,  'hf-internal-testing/tiny-bert' ,  vision_from_pt=lowercase ,  text_from_pt=lowercase ,  )
          a__						:     Dict			=    13
          a__						:     Any			=    floats_tensor(
              [
                  batch_size,
                  model.config.vision_config.num_channels,
                  model.config.vision_config.image_size,
                  model.config.vision_config.image_size,
              ])
          a__						:     Any			=    ids_tensor([batch_size, 4] ,  model.config.text_config.vocab_size)
          a__						:     str			=    random_attention_mask([batch_size, 4])
          a__						:     int			=    {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

          return model, inputs

   def 							__lowercase		( self ,  lowercase ,  lowercase)      ->						int:







          '''simple docstring'''

          a__						:     Optional[int]			=    FlaxCLIPVisionModel(lowercase)
          a__						:     Dict			=    FlaxBertModel(lowercase)
          return vision_model, text_model

   def 							__lowercase		( self)      ->						List[str]:







          '''simple docstring'''

          a__						:     Tuple			=    FlaxCLIPVisionModelTester(self)
          a__						:     int			=    FlaxBertModelTester(self)
          a__						:     int			=    clip_model_tester.prepare_config_and_inputs()
          a__						:     int			=    bert_model_tester.prepare_config_and_inputs()

          a__			,							a__						:     Any			=    vision_config_and_inputs

          a__			,							a__			,							a__			,							a__						:     Tuple			=    text_config_and_inputs

          # make sure that cross attention layers are added
          return {
              "text_config": text_config,
              "vision_config": vision_config,
              "pixel_values": pixel_values,
              "attention_mask": attention_mask,
              "input_ids": input_ids,
              "token_type_ids": token_type_ids,
          }





@require_flax
@require_vision
class 			A__   (							unittest.TestCase     ):




   """simple docstring"""



   @slow
   def 							__lowercase		( self)      ->						List[Any]:







          '''simple docstring'''

          a__						:     List[str]			=    FlaxVisionTextDualEncoderModel.from_pretrained('clip-italian/clip-italian' ,  logit_scale_init_value=1.0)
          a__						:     Tuple			=    VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian')

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

          a__						:     Any			=    model(**lowercase)

          # 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]) ,  )

          a__						:     int			=    np.array([[1.2_28_47_27, 0.3_10_41_22]])

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









import glob
import os
import random
from string import ascii_lowercase, digits

import cva
lowercase				:	Optional[Any]      						=  """"""
lowercase				:	int      						=  """"""
lowercase				:	List[Any]      						=  """"""
lowercase				:	Optional[int]      						=  1  # (0 is vertical, 1 is horizontal)



def A_     (		)  ->		None:
       a__			,							a__						:     str			=    get_dataset(A__		,				A__    )
       print('Processing...'    )
       a__			,							a__			,							a__						:     Tuple			=    update_image_and_anno(A__		,				A__		,				A__    )

       for index, image in enumerate(A__    ):
              # Get random string code: '7b7ad245cdff75241935e4dd860f3bad'
              a__						:     int			=    random_chars(32    )
              a__						:     Optional[Any]			=    paths[index].split(os.sep    )[-1].rsplit('.'		,				1    )[0]
              a__						:     Optional[int]			=    F'{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}'
              cva.imwrite(F'/{file_root}.jpg'		,				A__		,				[cva.IMWRITE_JPEG_QUALITY, 85]    )
              print(F'Success {index+1}/{len(A__    )} with {file_name}'    )
              a__						:     List[str]			=    []
              for anno in new_annos[index]:
                     a__						:     Union[str, Any]			=    F'{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}'
                     annos_list.append(A__    )
              with open(F'/{file_root}.txt'		,				'w'    ) as outfile:
                     outfile.write('\n'.join(line for line in annos_list    )    )



def A_     (		A__		,				A__    )  ->		tuple[list, list]:
       a__						:     int			=    []
       a__						:     int			=    []
       for label_file in glob.glob(os.path.join(A__		,				'*.txt'    )    ):
              a__						:     Optional[Any]			=    label_file.split(os.sep    )[-1].rsplit('.'		,				1    )[0]
              with open(A__    ) as in_file:
                     a__						:     Tuple			=    in_file.readlines()
              a__						:     Dict			=    os.path.join(A__		,				F'{label_name}.jpg'    )

              a__						:     int			=    []
              for obj_list in obj_lists:
                     a__						:     Union[str, Any]			=    obj_list.rstrip('\n'    ).split(' '    )
                     boxes.append(
                         [
                             int(obj[0]    ),
                             float(obj[1]    ),
                             float(obj[2]    ),
                             float(obj[3]    ),
                             float(obj[4]    ),
                         ]    )
              if not boxes:
                     continue
              img_paths.append(A__    )
              labels.append(A__    )
       return img_paths, labels



def A_     (		A__		,				A__		,				A__ = 1    )  ->		tuple[list, list, list]:
       a__						:     Optional[int]			=    []
       a__						:     Any			=    []
       a__						:     Dict			=    []
       for idx in range(len(A__    )    ):
              a__						:     Optional[int]			=    []
              a__						:     Optional[Any]			=    img_list[idx]
              path_list.append(A__    )
              a__						:     Union[str, Any]			=    anno_list[idx]
              a__						:     List[str]			=    cva.imread(A__    )
              if flip_type == 1:
                     a__						:     List[str]			=    cva.flip(A__		,				A__    )
                     for bbox in img_annos:
                            a__						:     Optional[Any]			=    1 - bbox[1]
                            new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]]    )
              elif flip_type == 0:
                     a__						:     Optional[Any]			=    cva.flip(A__		,				A__    )
                     for bbox in img_annos:
                            a__						:     Optional[int]			=    1 - bbox[2]
                            new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]]    )
              new_annos_lists.append(A__    )
              new_imgs_list.append(A__    )
       return new_imgs_list, new_annos_lists, path_list



def A_     (		A__ = 32    )  ->		str:
       assert number_char > 1, "The number of character should greater than 1"
       a__						:     Optional[int]			=    ascii_lowercase + digits
       return "".join(random.choice(A__    ) for _ in range(A__    )    )


if __name__ == "__main__":
    main()
    print("""DONE ✅""")


