






import json
import os
import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers import CLIPTokenizer, CLIPTokenizerFast
from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES
from transformers.testing_utils import require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available


if is_vision_available():
 from PIL import Image

 from transformers import OwlViTImageProcessor, OwlViTProcessor







@require_vision
class 	_UpperCAmelCase  (  unittest.TestCase		):




      """simple docstring"""



      def 			snake_case_      (   self		):



          '''simple docstring'''
          lowerCAmelCase__   :Optional[int]      							=				tempfile.mkdtemp()

          # fmt: off
          lowerCAmelCase__   :Optional[int]      							=				["", "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "lo", "l</w>", "w</w>", "r</w>", "t</w>", "low</w>", "er</w>", "lowest</w>", "newer</w>", "wider", "<unk>", "<|startoftext|>", "<|endoftext|>"]
          # fmt: on
          lowerCAmelCase__   :List[str]      							=				dict(zip(_lowerCAmelCase    ,	range(len(_lowerCAmelCase		)		)		)		)
          lowerCAmelCase__   :Optional[int]      							=				["#version: 0.2", "l o", "lo w</w>", "e r</w>", ""]
          lowerCAmelCase__   :Optional[Any]      							=				{"unk_token": "<unk>"}

          lowerCAmelCase__   :int      							=				os.path.join(self.tmpdirname    ,	VOCAB_FILES_NAMES["vocab_file"]		)
          lowerCAmelCase__   :List[Any]      							=				os.path.join(self.tmpdirname    ,	VOCAB_FILES_NAMES["merges_file"]		)
          with open(self.vocab_file    ,	"w"    ,	encoding="utf-8"		) as fp:
              fp.write(json.dumps(_lowerCAmelCase		) + "\n"		)
          with open(self.merges_file    ,	"w"    ,	encoding="utf-8"		) as fp:
              fp.write("\n".join(_lowerCAmelCase		)		)

          lowerCAmelCase__   :str      							=				{
              "do_resize": True,
              "size": 20,
              "do_center_crop": True,
              "crop_size": 18,
              "do_normalize": True,
              "image_mean": [0.4814_5466, 0.457_8275, 0.4082_1073],
              "image_std": [0.2686_2954, 0.2613_0258, 0.2757_7711],
          }
          lowerCAmelCase__   :str      							=				os.path.join(self.tmpdirname    ,	_lowerCAmelCase		)
          with open(self.image_processor_file    ,	"w"    ,	encoding="utf-8"		) as fp:
              json.dump(_lowerCAmelCase    ,	_lowerCAmelCase		)
      def 			snake_case_      (   self    ,	**_lowerCAmelCase		):



          '''simple docstring'''
          return CLIPTokenizer.from_pretrained(self.tmpdirname    ,	pad_token="!"    ,	**_lowerCAmelCase		)
      def 			snake_case_      (   self    ,	**_lowerCAmelCase		):



          '''simple docstring'''
          return CLIPTokenizerFast.from_pretrained(self.tmpdirname    ,	pad_token="!"    ,	**_lowerCAmelCase		)
      def 			snake_case_      (   self    ,	**_lowerCAmelCase		):



          '''simple docstring'''
          return OwlViTImageProcessor.from_pretrained(self.tmpdirname    ,	**_lowerCAmelCase		)
      def 			snake_case_      (   self		):



          '''simple docstring'''
          shutil.rmtree(self.tmpdirname		)
      def 			snake_case_      (   self		):



          '''simple docstring'''
          lowerCAmelCase__   :Optional[int]      							=				[np.random.randint(255    ,	size=(3, 30, 400)    ,	dtype=np.uinta		)]

          lowerCAmelCase__   :Optional[Any]      							=				[Image.fromarray(np.moveaxis(_lowerCAmelCase    ,	0    ,	-1		)		) for x in image_inputs]

          return image_inputs
      def 			snake_case_      (   self		):



          '''simple docstring'''
          lowerCAmelCase__   :int      							=				self.get_tokenizer()
          lowerCAmelCase__   :Any      							=				self.get_rust_tokenizer()
          lowerCAmelCase__   :Any      							=				self.get_image_processor()

          lowerCAmelCase__   :Optional[int]      							=				OwlViTProcessor(tokenizer=_lowerCAmelCase    ,	image_processor=_lowerCAmelCase		)
          processor_slow.save_pretrained(self.tmpdirname		)
          lowerCAmelCase__   :Tuple      							=				OwlViTProcessor.from_pretrained(self.tmpdirname    ,	use_fast=_lowerCAmelCase		)

          lowerCAmelCase__   :Tuple      							=				OwlViTProcessor(tokenizer=_lowerCAmelCase    ,	image_processor=_lowerCAmelCase		)
          processor_fast.save_pretrained(self.tmpdirname		)
          lowerCAmelCase__   :Optional[int]      							=				OwlViTProcessor.from_pretrained(self.tmpdirname		)

          self.assertEqual(processor_slow.tokenizer.get_vocab()    ,	tokenizer_slow.get_vocab()		)
          self.assertEqual(processor_fast.tokenizer.get_vocab()    ,	tokenizer_fast.get_vocab()		)
          self.assertEqual(tokenizer_slow.get_vocab()    ,	tokenizer_fast.get_vocab()		)
          self.assertIsInstance(processor_slow.tokenizer    ,	_lowerCAmelCase		)
          self.assertIsInstance(processor_fast.tokenizer    ,	_lowerCAmelCase		)

          self.assertEqual(processor_slow.image_processor.to_json_string()    ,	image_processor.to_json_string()		)
          self.assertEqual(processor_fast.image_processor.to_json_string()    ,	image_processor.to_json_string()		)
          self.assertIsInstance(processor_slow.image_processor    ,	_lowerCAmelCase		)
          self.assertIsInstance(processor_fast.image_processor    ,	_lowerCAmelCase		)
      def 			snake_case_      (   self		):



          '''simple docstring'''
          lowerCAmelCase__   :List[str]      							=				OwlViTProcessor(tokenizer=self.get_tokenizer()    ,	image_processor=self.get_image_processor()		)
          processor.save_pretrained(self.tmpdirname		)

          lowerCAmelCase__   :List[str]      							=				self.get_tokenizer(bos_token="(BOS)"    ,	eos_token="(EOS)"		)
          lowerCAmelCase__   :Optional[int]      							=				self.get_image_processor(do_normalize=_lowerCAmelCase		)

          lowerCAmelCase__   :Optional[Any]      							=				OwlViTProcessor.from_pretrained(
              self.tmpdirname    ,	bos_token="(BOS)"    ,	eos_token="(EOS)"    ,	do_normalize=_lowerCAmelCase		)

          self.assertEqual(processor.tokenizer.get_vocab()    ,	tokenizer_add_kwargs.get_vocab()		)
          self.assertIsInstance(processor.tokenizer    ,	_lowerCAmelCase		)

          self.assertEqual(processor.image_processor.to_json_string()    ,	image_processor_add_kwargs.to_json_string()		)
          self.assertIsInstance(processor.image_processor    ,	_lowerCAmelCase		)
      def 			snake_case_      (   self		):



          '''simple docstring'''
          lowerCAmelCase__   :int      							=				self.get_image_processor()
          lowerCAmelCase__   :List[str]      							=				self.get_tokenizer()

          lowerCAmelCase__   :List[Any]      							=				OwlViTProcessor(tokenizer=_lowerCAmelCase    ,	image_processor=_lowerCAmelCase		)

          lowerCAmelCase__   :List[str]      							=				self.prepare_image_inputs()

          lowerCAmelCase__   :Any      							=				image_processor(_lowerCAmelCase    ,	return_tensors="np"		)
          lowerCAmelCase__   :Union[str, Any]      							=				processor(images=_lowerCAmelCase    ,	return_tensors="np"		)

          for key in input_image_proc.keys():
              self.assertAlmostEqual(input_image_proc[key].sum()    ,	input_processor[key].sum()    ,	delta=1e-2		)
      def 			snake_case_      (   self		):



          '''simple docstring'''
          lowerCAmelCase__   :Optional[int]      							=				self.get_image_processor()
          lowerCAmelCase__   :Union[str, Any]      							=				self.get_tokenizer()

          lowerCAmelCase__   :str      							=				OwlViTProcessor(tokenizer=_lowerCAmelCase    ,	image_processor=_lowerCAmelCase		)

          lowerCAmelCase__   :Dict      							=				"lower newer"

          lowerCAmelCase__   :Union[str, Any]      							=				processor(text=_lowerCAmelCase    ,	return_tensors="np"		)

          lowerCAmelCase__   :List[Any]      							=				tokenizer(_lowerCAmelCase    ,	return_tensors="np"		)

          for key in encoded_tok.keys():
              self.assertListEqual(encoded_tok[key][0].tolist()    ,	encoded_processor[key][0].tolist()		)
      def 			snake_case_      (   self		):



          '''simple docstring'''
          lowerCAmelCase__   :str      							=				self.get_image_processor()
          lowerCAmelCase__   :Optional[Any]      							=				self.get_tokenizer()

          lowerCAmelCase__   :Optional[int]      							=				OwlViTProcessor(tokenizer=_lowerCAmelCase    ,	image_processor=_lowerCAmelCase		)

          lowerCAmelCase__   :Dict      							=				"lower newer"
          lowerCAmelCase__   :List[str]      							=				self.prepare_image_inputs()

          lowerCAmelCase__   :Optional[Any]      							=				processor(text=_lowerCAmelCase    ,	images=_lowerCAmelCase		)

          self.assertListEqual(list(inputs.keys()		)    ,	["input_ids", "attention_mask", "pixel_values"]		)

          # test if it raises when no input is passed
          with pytest.raises(_lowerCAmelCase		):
              processor()
      def 			snake_case_      (   self		):



          '''simple docstring'''
          lowerCAmelCase__   :Any      							=				"google/owlvit-base-patch32"
          lowerCAmelCase__   :List[Any]      							=				OwlViTProcessor.from_pretrained(_lowerCAmelCase		)

          lowerCAmelCase__   :Tuple      							=				["cat", "nasa badge"]
          lowerCAmelCase__   :Any      							=				processor(text=_lowerCAmelCase		)

          lowerCAmelCase__   :str      							=				16
          self.assertListEqual(list(inputs.keys()		)    ,	["input_ids", "attention_mask"]		)
          self.assertEqual(inputs["input_ids"].shape    ,	(2, seq_length)		)

          # test if it raises when no input is passed
          with pytest.raises(_lowerCAmelCase		):
              processor()
      def 			snake_case_      (   self		):



          '''simple docstring'''
          lowerCAmelCase__   :Optional[Any]      							=				"google/owlvit-base-patch32"
          lowerCAmelCase__   :Optional[Any]      							=				OwlViTProcessor.from_pretrained(_lowerCAmelCase		)

          lowerCAmelCase__   :Union[str, Any]      							=				[["cat", "nasa badge"], ["person"]]
          lowerCAmelCase__   :str      							=				processor(text=_lowerCAmelCase		)

          lowerCAmelCase__   :Optional[Any]      							=				16
          lowerCAmelCase__   :List[str]      							=				len(_lowerCAmelCase		)
          lowerCAmelCase__   :Union[str, Any]      							=				max([len(_lowerCAmelCase		) for texts in input_texts]		)

          self.assertListEqual(list(inputs.keys()		)    ,	["input_ids", "attention_mask"]		)
          self.assertEqual(inputs["input_ids"].shape    ,	(batch_size * num_max_text_queries, seq_length)		)

          # test if it raises when no input is passed
          with pytest.raises(_lowerCAmelCase		):
              processor()
      def 			snake_case_      (   self		):



          '''simple docstring'''
          lowerCAmelCase__   :str      							=				"google/owlvit-base-patch32"
          lowerCAmelCase__   :Dict      							=				OwlViTProcessor.from_pretrained(_lowerCAmelCase		)

          lowerCAmelCase__   :List[Any]      							=				["cat", "nasa badge"]
          lowerCAmelCase__   :Optional[Any]      							=				processor(text=_lowerCAmelCase		)

          lowerCAmelCase__   :Optional[Any]      							=				16
          lowerCAmelCase__   :Any      							=				inputs["input_ids"]
          lowerCAmelCase__   :List[str]      							=				[
              [49_406, 2_368, 49_407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
              [49_406, 6_841, 11_301, 49_407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
          ]

          self.assertListEqual(list(inputs.keys()		)    ,	["input_ids", "attention_mask"]		)
          self.assertEqual(inputs["input_ids"].shape    ,	(2, seq_length)		)
          self.assertListEqual(list(input_ids[0]		)    ,	predicted_ids[0]		)
          self.assertListEqual(list(input_ids[1]		)    ,	predicted_ids[1]		)
      def 			snake_case_      (   self		):



          '''simple docstring'''
          lowerCAmelCase__   :List[Any]      							=				self.get_image_processor()
          lowerCAmelCase__   :Dict      							=				self.get_tokenizer()

          lowerCAmelCase__   :Tuple      							=				OwlViTProcessor(tokenizer=_lowerCAmelCase    ,	image_processor=_lowerCAmelCase		)

          lowerCAmelCase__   :Any      							=				self.prepare_image_inputs()
          lowerCAmelCase__   :str      							=				self.prepare_image_inputs()

          lowerCAmelCase__   :Union[str, Any]      							=				processor(images=_lowerCAmelCase    ,	query_images=_lowerCAmelCase		)

          self.assertListEqual(list(inputs.keys()		)    ,	["query_pixel_values", "pixel_values"]		)

          # test if it raises when no input is passed
          with pytest.raises(_lowerCAmelCase		):
              processor()



      def 			snake_case_      (   self		):



          '''simple docstring'''
          lowerCAmelCase__   :Tuple      							=				self.get_image_processor()
          lowerCAmelCase__   :Optional[int]      							=				self.get_tokenizer()

          lowerCAmelCase__   :Any      							=				OwlViTProcessor(tokenizer=_lowerCAmelCase    ,	image_processor=_lowerCAmelCase		)

          lowerCAmelCase__   :Any      							=				[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

          lowerCAmelCase__   :Any      							=				processor.batch_decode(_lowerCAmelCase		)
          lowerCAmelCase__   :List[str]      							=				tokenizer.batch_decode(_lowerCAmelCase		)

          self.assertListEqual(_lowerCAmelCase    ,	_lowerCAmelCase		)











from __future__ import annotations

import numpy as np


def 				snake_case__							(							UpperCAmelCase							:  np.ndarray       ):
    lowerCAmelCase__							,lowerCAmelCase__   :List[str]      							=				np.shape(UpperCAmelCase       )
    if rows != columns:
        lowerCAmelCase__   :Tuple      							=				(
            "'table' has to be of square shaped array but got a "
            F'''{rows}x{columns} array:\n{table}'''
        )
        raise ValueError(UpperCAmelCase       )

    lowerCAmelCase__   :Optional[Any]      							=				np.zeros((rows, columns)       )
    lowerCAmelCase__   :Tuple      							=				np.zeros((rows, columns)       )
    for i in range(UpperCAmelCase       ):
        for j in range(UpperCAmelCase       ):
            lowerCAmelCase__   :Any      							=				sum(lower[i][k] * upper[k][j] for k in range(UpperCAmelCase       )       )
            if upper[j][j] == 0:
                raise ArithmeticError("No LU decomposition exists"       )
            lowerCAmelCase__   :Any      							=				(table[i][j] - total) / upper[j][j]
        lowerCAmelCase__   :Tuple      							=				1
        for j in range(UpperCAmelCase    ,			UpperCAmelCase       ):
            lowerCAmelCase__   :Optional[Any]      							=				sum(lower[i][k] * upper[k][j] for k in range(UpperCAmelCase       )       )
            lowerCAmelCase__   :Dict      							=				table[i][j] - total
    return lower, upper


if __name__ == "__main__":
 import doctest

 doctest.testmod()



