


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							):






		def _snake_case		(						self				:     List[str]):
				SCREAMING_SNAKE_CASE_				:List[Any]				     =						tempfile.mkdtemp()

				# fmt: off
				SCREAMING_SNAKE_CASE_				:Tuple				     =						["", "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
				SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						dict(zip(UpperCAmelCase   ,  range(len(UpperCAmelCase))))
				SCREAMING_SNAKE_CASE_				:List[Any]				     =						["#version: 0.2", "l o", "lo w</w>", "e r</w>", ""]
				SCREAMING_SNAKE_CASE_				:List[Any]				     =						{"unk_token": "<unk>"}

				SCREAMING_SNAKE_CASE_				:Any				     =						os.path.join(self.tmpdirname   ,  VOCAB_FILES_NAMES["vocab_file"])
				SCREAMING_SNAKE_CASE_				: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(UpperCAmelCase) + "\n")
				with open(self.merges_file   ,  "w"   ,  encoding="utf-8") as fp:
						fp.write("\n".join(UpperCAmelCase))

				SCREAMING_SNAKE_CASE_				:Optional[Any]				     =						{
				    "do_resize": True,
				    "size": 20,
				    "do_center_crop": True,
				    "crop_size": 18,
				    "do_normalize": True,
				    "image_mean": [0.48145466, 0.4578275, 0.40821073],
				    "image_std": [0.26862954, 0.26130258, 0.27577711],
				}
				SCREAMING_SNAKE_CASE_				:List[str]				     =						os.path.join(self.tmpdirname   ,  UpperCAmelCase)
				with open(self.image_processor_file   ,  "w"   ,  encoding="utf-8") as fp:
						json.dump(UpperCAmelCase   ,  UpperCAmelCase)






		def _snake_case		(						self				:     List[str]   ,  **UpperCAmelCase				:     Optional[Any]):
				return CLIPTokenizer.from_pretrained(self.tmpdirname   ,  pad_token="!"   ,  **UpperCAmelCase)






		def _snake_case		(						self				:     List[str]   ,  **UpperCAmelCase				:     List[Any]):
				return CLIPTokenizerFast.from_pretrained(self.tmpdirname   ,  pad_token="!"   ,  **UpperCAmelCase)






		def _snake_case		(						self				:     Any   ,  **UpperCAmelCase				:     str):
				return OwlViTImageProcessor.from_pretrained(self.tmpdirname   ,  **UpperCAmelCase)






		def _snake_case		(						self				:     Any):
				shutil.rmtree(self.tmpdirname)






		def _snake_case		(						self				:     Union[str, Any]):
				SCREAMING_SNAKE_CASE_				:Optional[int]				     =						[np.random.randint(2_55   ,  size=(3, 30, 4_00)   ,  dtype=np.uinta)]

				SCREAMING_SNAKE_CASE_				:Optional[int]				     =						[Image.fromarray(np.moveaxis(UpperCAmelCase   ,  0   ,  -1)) for x in image_inputs]

				return image_inputs






		def _snake_case		(						self				:     Optional[int]):
				SCREAMING_SNAKE_CASE_				:Optional[int]				     =						self.get_tokenizer()
				SCREAMING_SNAKE_CASE_				:List[Any]				     =						self.get_rust_tokenizer()
				SCREAMING_SNAKE_CASE_				:Any				     =						self.get_image_processor()

				SCREAMING_SNAKE_CASE_				:str				     =						OwlViTProcessor(tokenizer=UpperCAmelCase   ,  image_processor=UpperCAmelCase)
				processor_slow.save_pretrained(self.tmpdirname)
				SCREAMING_SNAKE_CASE_				:Any				     =						OwlViTProcessor.from_pretrained(self.tmpdirname   ,  use_fast=UpperCAmelCase)

				SCREAMING_SNAKE_CASE_				:List[str]				     =						OwlViTProcessor(tokenizer=UpperCAmelCase   ,  image_processor=UpperCAmelCase)
				processor_fast.save_pretrained(self.tmpdirname)
				SCREAMING_SNAKE_CASE_				: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   ,  UpperCAmelCase)
				self.assertIsInstance(processor_fast.tokenizer   ,  UpperCAmelCase)

				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   ,  UpperCAmelCase)
				self.assertIsInstance(processor_fast.image_processor   ,  UpperCAmelCase)






		def _snake_case		(						self				:     Any):
				SCREAMING_SNAKE_CASE_				:Optional[Any]				     =						OwlViTProcessor(tokenizer=self.get_tokenizer()   ,  image_processor=self.get_image_processor())
				processor.save_pretrained(self.tmpdirname)

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

				SCREAMING_SNAKE_CASE_				:List[Any]				     =						OwlViTProcessor.from_pretrained(
				    self.tmpdirname   ,  bos_token="(BOS)"   ,  eos_token="(EOS)"   ,  do_normalize=UpperCAmelCase)

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

				self.assertEqual(processor.image_processor.to_json_string()   ,  image_processor_add_kwargs.to_json_string())
				self.assertIsInstance(processor.image_processor   ,  UpperCAmelCase)






		def _snake_case		(						self				:     Optional[int]):
				SCREAMING_SNAKE_CASE_				:Optional[Any]				     =						self.get_image_processor()
				SCREAMING_SNAKE_CASE_				:int				     =						self.get_tokenizer()

				SCREAMING_SNAKE_CASE_				:Optional[Any]				     =						OwlViTProcessor(tokenizer=UpperCAmelCase   ,  image_processor=UpperCAmelCase)

				SCREAMING_SNAKE_CASE_				:Dict				     =						self.prepare_image_inputs()

				SCREAMING_SNAKE_CASE_				:Optional[Any]				     =						image_processor(UpperCAmelCase   ,  return_tensors="np")
				SCREAMING_SNAKE_CASE_				:Dict				     =						processor(images=UpperCAmelCase   ,  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				:     Tuple):
				SCREAMING_SNAKE_CASE_				:str				     =						self.get_image_processor()
				SCREAMING_SNAKE_CASE_				:List[str]				     =						self.get_tokenizer()

				SCREAMING_SNAKE_CASE_				:List[str]				     =						OwlViTProcessor(tokenizer=UpperCAmelCase   ,  image_processor=UpperCAmelCase)

				SCREAMING_SNAKE_CASE_				:str				     =						"lower newer"

				SCREAMING_SNAKE_CASE_				:int				     =						processor(text=UpperCAmelCase   ,  return_tensors="np")

				SCREAMING_SNAKE_CASE_				:List[str]				     =						tokenizer(UpperCAmelCase   ,  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				:     Optional[Any]):
				SCREAMING_SNAKE_CASE_				:Tuple				     =						self.get_image_processor()
				SCREAMING_SNAKE_CASE_				:Dict				     =						self.get_tokenizer()

				SCREAMING_SNAKE_CASE_				:List[str]				     =						OwlViTProcessor(tokenizer=UpperCAmelCase   ,  image_processor=UpperCAmelCase)

				SCREAMING_SNAKE_CASE_				:Any				     =						"lower newer"
				SCREAMING_SNAKE_CASE_				:Any				     =						self.prepare_image_inputs()

				SCREAMING_SNAKE_CASE_				:Optional[int]				     =						processor(text=UpperCAmelCase   ,  images=UpperCAmelCase)

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

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






		def _snake_case		(						self				:     Union[str, Any]):
				SCREAMING_SNAKE_CASE_				:str				     =						"google/owlvit-base-patch32"
				SCREAMING_SNAKE_CASE_				:int				     =						OwlViTProcessor.from_pretrained(UpperCAmelCase)

				SCREAMING_SNAKE_CASE_				:Optional[int]				     =						["cat", "nasa badge"]
				SCREAMING_SNAKE_CASE_				:Optional[int]				     =						processor(text=UpperCAmelCase)

				SCREAMING_SNAKE_CASE_				:Dict				     =						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(UpperCAmelCase):
						processor()






		def _snake_case		(						self				:     int):
				SCREAMING_SNAKE_CASE_				:str				     =						"google/owlvit-base-patch32"
				SCREAMING_SNAKE_CASE_				:List[Any]				     =						OwlViTProcessor.from_pretrained(UpperCAmelCase)

				SCREAMING_SNAKE_CASE_				:str				     =						[["cat", "nasa badge"], ["person"]]
				SCREAMING_SNAKE_CASE_				:Optional[Any]				     =						processor(text=UpperCAmelCase)

				SCREAMING_SNAKE_CASE_				:Any				     =						16
				SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						len(UpperCAmelCase)
				SCREAMING_SNAKE_CASE_				:List[str]				     =						max([len(UpperCAmelCase) 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(UpperCAmelCase):
						processor()






		def _snake_case		(						self				:     List[str]):
				SCREAMING_SNAKE_CASE_				:Any				     =						"google/owlvit-base-patch32"
				SCREAMING_SNAKE_CASE_				:Optional[Any]				     =						OwlViTProcessor.from_pretrained(UpperCAmelCase)

				SCREAMING_SNAKE_CASE_				:Any				     =						["cat", "nasa badge"]
				SCREAMING_SNAKE_CASE_				:str				     =						processor(text=UpperCAmelCase)

				SCREAMING_SNAKE_CASE_				:Any				     =						16
				SCREAMING_SNAKE_CASE_				:Optional[int]				     =						inputs["input_ids"]
				SCREAMING_SNAKE_CASE_				:int				     =						[
				    [4_94_06, 23_68, 4_94_07, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
				    [4_94_06, 68_41, 1_13_01, 4_94_07, 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				:     List[Any]):
				SCREAMING_SNAKE_CASE_				:Any				     =						self.get_image_processor()
				SCREAMING_SNAKE_CASE_				:List[str]				     =						self.get_tokenizer()

				SCREAMING_SNAKE_CASE_				:List[Any]				     =						OwlViTProcessor(tokenizer=UpperCAmelCase   ,  image_processor=UpperCAmelCase)

				SCREAMING_SNAKE_CASE_				:Dict				     =						self.prepare_image_inputs()
				SCREAMING_SNAKE_CASE_				:Dict				     =						self.prepare_image_inputs()

				SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						processor(images=UpperCAmelCase   ,  query_images=UpperCAmelCase)

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

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







		def _snake_case		(						self				:     List[Any]):
				SCREAMING_SNAKE_CASE_				:List[Any]				     =						self.get_image_processor()
				SCREAMING_SNAKE_CASE_				:Any				     =						self.get_tokenizer()

				SCREAMING_SNAKE_CASE_				:List[str]				     =						OwlViTProcessor(tokenizer=UpperCAmelCase   ,  image_processor=UpperCAmelCase)

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

				SCREAMING_SNAKE_CASE_				:str				     =						processor.batch_decode(UpperCAmelCase)
				SCREAMING_SNAKE_CASE_				:Any				     =						tokenizer.batch_decode(UpperCAmelCase)

				self.assertListEqual(UpperCAmelCase   ,  UpperCAmelCase)










from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
    is_vision_available,
)


SCREAMING_SNAKE_CASE__     					=			{
    "configuration_owlvit": [
        "OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP",
        "OwlViTConfig",
        "OwlViTOnnxConfig",
        "OwlViTTextConfig",
        "OwlViTVisionConfig",
    ],
    "processing_owlvit": ["OwlViTProcessor"],
}


try:
		if not is_vision_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		SCREAMING_SNAKE_CASE__     					=			["OwlViTFeatureExtractor"]
		SCREAMING_SNAKE_CASE__     					=			["OwlViTImageProcessor"]

try:
		if not is_torch_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		SCREAMING_SNAKE_CASE__     					=			[
		    "OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST",
		    "OwlViTModel",
		    "OwlViTPreTrainedModel",
		    "OwlViTTextModel",
		    "OwlViTVisionModel",
		    "OwlViTForObjectDetection",
		]

if TYPE_CHECKING:
		from .configuration_owlvit import (
		    OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP,
		    OwlViTConfig,
		    OwlViTOnnxConfig,
		    OwlViTTextConfig,
		    OwlViTVisionConfig,
		)
		from .processing_owlvit import OwlViTProcessor

		try:
				if not is_vision_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .feature_extraction_owlvit import OwlViTFeatureExtractor
				from .image_processing_owlvit import OwlViTImageProcessor

		try:
				if not is_torch_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_owlvit import (
				    OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST,
				    OwlViTForObjectDetection,
				    OwlViTModel,
				    OwlViTPreTrainedModel,
				    OwlViTTextModel,
				    OwlViTVisionModel,
				)

else:
		import sys

		SCREAMING_SNAKE_CASE__     					=			_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)






