



import copy
import os
from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Dict, Mapping, Optional, Union


if TYPE_CHECKING:
							from ...processing_utils import ProcessorMixin
							from ...utils import TensorType

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


__snake_case    :		Any  =logging.get_logger(__name__)

__snake_case    :		Union[str, Any]  ={
    'google/owlvit-base-patch32': 'https://huggingface.co/google/owlvit-base-patch32/resolve/main/config.json',
    'google/owlvit-base-patch16': 'https://huggingface.co/google/owlvit-base-patch16/resolve/main/config.json',
    'google/owlvit-large-patch14': 'https://huggingface.co/google/owlvit-large-patch14/resolve/main/config.json',
}



class 	lowerCamelCase__      (							lowerCamelCase__):




		'''simple docstring'''



		snake_case_     ="""owlvit_text_model"""



		def __init__(self		,__lowerCamelCase=4_94_08		,__lowerCamelCase=5_12		,__lowerCamelCase=20_48		,__lowerCamelCase=12		,__lowerCamelCase=8		,__lowerCamelCase=16		,__lowerCamelCase="quick_gelu"		,__lowerCamelCase=1e-5		,__lowerCamelCase=0.0		,__lowerCamelCase=0.02		,__lowerCamelCase=1.0		,__lowerCamelCase=0		,__lowerCamelCase=4_94_06		,__lowerCamelCase=4_94_07		,**__lowerCamelCase		,)					->      List[str]:

						"""simple docstring"""






						super().__init__(pad_token_id=__lowerCamelCase		,bos_token_id=__lowerCamelCase		,eos_token_id=__lowerCamelCase		,**__lowerCamelCase			)

						lowerCAmelCase__					:    Optional[Any]												=					vocab_size
						lowerCAmelCase__					:    int												=					hidden_size
						lowerCAmelCase__					:    Union[str, Any]												=					intermediate_size
						lowerCAmelCase__					:    Optional[int]												=					num_hidden_layers
						lowerCAmelCase__					:    str												=					num_attention_heads
						lowerCAmelCase__					:    Any												=					max_position_embeddings
						lowerCAmelCase__					:    Optional[Any]												=					hidden_act
						lowerCAmelCase__					:    Optional[int]												=					layer_norm_eps
						lowerCAmelCase__					:    str												=					attention_dropout
						lowerCAmelCase__					:    List[Any]												=					initializer_range
						lowerCAmelCase__					:    Optional[int]												=					initializer_factor



		@classmethod
		def 		lowerCAmelCase__				(cls		,__lowerCamelCase		,**__lowerCamelCase			)					->      "PretrainedConfig":

						"""simple docstring"""






						cls._set_token_in_kwargs(__lowerCamelCase			)

						lowerCAmelCase__						,		lowerCAmelCase__					:    List[str]												=					cls.get_config_dict(__lowerCamelCase		,**__lowerCamelCase			)

						# get the text config dict if we are loading from OwlViTConfig
						if config_dict.get('''model_type'''			) == "owlvit":
										lowerCAmelCase__					:    int												=					config_dict['''text_config''']

						if "model_type" in config_dict and hasattr(cls		,'''model_type'''			) and config_dict["model_type"] != cls.model_type:
										logger.warning(
										    f"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """
										    f"""{cls.model_type}. This is not supported for all configurations of models and can yield errors."""			)

						return cls.from_dict(__lowerCamelCase		,**__lowerCamelCase			)



class 	lowerCamelCase__      (							lowerCamelCase__):




		'''simple docstring'''



		snake_case_     ="""owlvit_vision_model"""



		def __init__(self		,__lowerCamelCase=7_68		,__lowerCamelCase=30_72		,__lowerCamelCase=12		,__lowerCamelCase=12		,__lowerCamelCase=3		,__lowerCamelCase=7_68		,__lowerCamelCase=32		,__lowerCamelCase="quick_gelu"		,__lowerCamelCase=1e-5		,__lowerCamelCase=0.0		,__lowerCamelCase=0.02		,__lowerCamelCase=1.0		,**__lowerCamelCase		,)					->      List[str]:

						"""simple docstring"""






						super().__init__(**__lowerCamelCase			)

						lowerCAmelCase__					:    Dict												=					hidden_size
						lowerCAmelCase__					:    Union[str, Any]												=					intermediate_size
						lowerCAmelCase__					:    int												=					num_hidden_layers
						lowerCAmelCase__					:    List[Any]												=					num_attention_heads
						lowerCAmelCase__					:    int												=					num_channels
						lowerCAmelCase__					:    Dict												=					image_size
						lowerCAmelCase__					:    Tuple												=					patch_size
						lowerCAmelCase__					:    int												=					hidden_act
						lowerCAmelCase__					:    str												=					layer_norm_eps
						lowerCAmelCase__					:    Tuple												=					attention_dropout
						lowerCAmelCase__					:    Optional[Any]												=					initializer_range
						lowerCAmelCase__					:    int												=					initializer_factor



		@classmethod
		def 		lowerCAmelCase__				(cls		,__lowerCamelCase		,**__lowerCamelCase			)					->      "PretrainedConfig":

						"""simple docstring"""






						cls._set_token_in_kwargs(__lowerCamelCase			)

						lowerCAmelCase__						,		lowerCAmelCase__					:    Optional[Any]												=					cls.get_config_dict(__lowerCamelCase		,**__lowerCamelCase			)

						# get the vision config dict if we are loading from OwlViTConfig
						if config_dict.get('''model_type'''			) == "owlvit":
										lowerCAmelCase__					:    int												=					config_dict['''vision_config''']

						if "model_type" in config_dict and hasattr(cls		,'''model_type'''			) and config_dict["model_type"] != cls.model_type:
										logger.warning(
										    f"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """
										    f"""{cls.model_type}. This is not supported for all configurations of models and can yield errors."""			)

						return cls.from_dict(__lowerCamelCase		,**__lowerCamelCase			)



class 	lowerCamelCase__      (							lowerCamelCase__):




		'''simple docstring'''



		snake_case_     ="""owlvit"""
		snake_case_     =True



		def __init__(self		,__lowerCamelCase=None		,__lowerCamelCase=None		,__lowerCamelCase=5_12		,__lowerCamelCase=2.6592		,__lowerCamelCase=True		,**__lowerCamelCase		,)					->      str:

						"""simple docstring"""






						super().__init__(**__lowerCamelCase			)

						if text_config is None:
										lowerCAmelCase__					:    List[Any]												=					{}
										logger.info('''text_config is None. Initializing the OwlViTTextConfig with default values.'''			)

						if vision_config is None:
										lowerCAmelCase__					:    Tuple												=					{}
										logger.info('''vision_config is None. initializing the OwlViTVisionConfig with default values.'''			)

						lowerCAmelCase__					:    List[str]												=					OwlViTTextConfig(**__lowerCamelCase			)
						lowerCAmelCase__					:    Tuple												=					OwlViTVisionConfig(**__lowerCamelCase			)

						lowerCAmelCase__					:    Union[str, Any]												=					projection_dim
						lowerCAmelCase__					:    Any												=					logit_scale_init_value
						lowerCAmelCase__					:    Union[str, Any]												=					return_dict
						lowerCAmelCase__					:    Optional[int]												=					1.0



		@classmethod
		def 		lowerCAmelCase__				(cls		,__lowerCamelCase		,**__lowerCamelCase			)					->      "PretrainedConfig":

						"""simple docstring"""






						cls._set_token_in_kwargs(__lowerCamelCase			)

						lowerCAmelCase__						,		lowerCAmelCase__					:    Tuple												=					cls.get_config_dict(__lowerCamelCase		,**__lowerCamelCase			)

						if "model_type" in config_dict and hasattr(cls		,'''model_type'''			) and config_dict["model_type"] != cls.model_type:
										logger.warning(
										    f"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """
										    f"""{cls.model_type}. This is not supported for all configurations of models and can yield errors."""			)

						return cls.from_dict(__lowerCamelCase		,**__lowerCamelCase			)



		@classmethod
		def 		lowerCAmelCase__				(cls		,__lowerCamelCase		,__lowerCamelCase		,**__lowerCamelCase			)					->      str:

						"""simple docstring"""






						lowerCAmelCase__					:    str												=					{}
						lowerCAmelCase__					:    List[str]												=					text_config
						lowerCAmelCase__					:    Optional[int]												=					vision_config

						return cls.from_dict(__lowerCamelCase		,**__lowerCamelCase			)



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

						"""simple docstring"""






						lowerCAmelCase__					:    Any												=					copy.deepcopy(self.__dict__			)
						lowerCAmelCase__					:    Tuple												=					self.text_config.to_dict()
						lowerCAmelCase__					:    Union[str, Any]												=					self.vision_config.to_dict()
						lowerCAmelCase__					:    List[Any]												=					self.__class__.model_type
						return output



class 	lowerCamelCase__      (							lowerCamelCase__):




		'''simple docstring'''



		@property
		def 		lowerCAmelCase__				(self			)					->      Mapping[str, Mapping[int, str]]:

						"""simple docstring"""






						return OrderedDict(
						    [
						        ('''input_ids''', {0: '''batch''', 1: '''sequence'''}),
						        ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
						        ('''attention_mask''', {0: '''batch''', 1: '''sequence'''}),
						    ]			)



		@property
		def 		lowerCAmelCase__				(self			)					->      Mapping[str, Mapping[int, str]]:

						"""simple docstring"""






						return OrderedDict(
						    [
						        ('''logits_per_image''', {0: '''batch'''}),
						        ('''logits_per_text''', {0: '''batch'''}),
						        ('''text_embeds''', {0: '''batch'''}),
						        ('''image_embeds''', {0: '''batch'''}),
						    ]			)



		@property
		def 		lowerCAmelCase__				(self			)					->      float:

						"""simple docstring"""






						return 1e-4



		def 		lowerCAmelCase__				(self		,__lowerCamelCase		,__lowerCamelCase = -1		,__lowerCamelCase = -1		,__lowerCamelCase = None		,)					->      Mapping[str, Any]:

						"""simple docstring"""






						lowerCAmelCase__					:    Optional[int]												=					super().generate_dummy_inputs(
						    processor.tokenizer		,batch_size=__lowerCamelCase		,seq_length=__lowerCamelCase		,framework=__lowerCamelCase			)
						lowerCAmelCase__					:    List[str]												=					super().generate_dummy_inputs(
						    processor.image_processor		,batch_size=__lowerCamelCase		,framework=__lowerCamelCase			)
						return {**text_input_dict, **image_input_dict}



		@property
		def 		lowerCAmelCase__				(self			)					->      int:

						"""simple docstring"""






						return 14






import itertools
import json
import linecache
import os
import pickle
import re
import socket
import string
from collections import Counter
from logging import getLogger
from pathlib import Path
from typing import Callable, Dict, Iterable, List

import git
import torch
from torch.utils.data import Dataset

from transformers import BartTokenizer, RagTokenizer, TaTokenizer






def      lowerCAmelCase__		(   lowerCamelCase_		:		int	,lowerCamelCase_		:		Optional[Any]	,lowerCamelCase_		:		Optional[int]	,lowerCamelCase_		:		Optional[int]	,lowerCamelCase_		:		Any=True	,lowerCamelCase_		:		Tuple="pt"):





				'''simple docstring'''

				lowerCAmelCase__					:    Tuple												=					{'''add_prefix_space''': True} if isinstance(lowerCamelCase_	,lowerCamelCase_) and not line.startswith(''' ''') else {}
				lowerCAmelCase__					:    Union[str, Any]												=					padding_side
				return tokenizer(
				    [line]	,max_length=lowerCamelCase_	,padding='''max_length''' if pad_to_max_length else None	,truncation=lowerCamelCase_	,return_tensors=lowerCamelCase_	,add_special_tokens=lowerCamelCase_	,**lowerCamelCase_	,)






def      lowerCAmelCase__		(   lowerCamelCase_		:		Optional[int]	,lowerCamelCase_		:		Dict	,lowerCamelCase_		:		Any=None	,):





				'''simple docstring'''

				lowerCAmelCase__					:    List[Any]												=					input_ids.ne(lowerCamelCase_).any(dim=0)
				if attention_mask is None:
								return input_ids[:, keep_column_mask]
				else:
								return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask])



class 	lowerCamelCase__      (							lowerCamelCase__):




		'''simple docstring'''



		def __init__(self		,__lowerCamelCase		,__lowerCamelCase		,__lowerCamelCase		,__lowerCamelCase		,__lowerCamelCase="train"		,__lowerCamelCase=None		,__lowerCamelCase=None		,__lowerCamelCase=None		,__lowerCamelCase=""		,)					->      List[str]:

						"""simple docstring"""






						super().__init__()
						lowerCAmelCase__					:    str												=					Path(__lowerCamelCase			).joinpath(type_path + '''.source'''			)
						lowerCAmelCase__					:    int												=					Path(__lowerCamelCase			).joinpath(type_path + '''.target'''			)
						lowerCAmelCase__					:    Tuple												=					self.get_char_lens(self.src_file			)
						lowerCAmelCase__					:    Dict												=					max_source_length
						lowerCAmelCase__					:    Optional[int]												=					max_target_length
						assert min(self.src_lens			) > 0, f"""found empty line in {self.src_file}"""
						lowerCAmelCase__					:    Tuple												=					tokenizer
						lowerCAmelCase__					:    List[Any]												=					prefix
						if n_obs is not None:
										lowerCAmelCase__					:    Optional[Any]												=					self.src_lens[:n_obs]
						lowerCAmelCase__					:    Any												=					src_lang
						lowerCAmelCase__					:    Optional[Any]												=					tgt_lang



		def __len__(self			)					->      str:

						"""simple docstring"""






						return len(self.src_lens			)



		def __getitem__(self		,__lowerCamelCase			)					->      Dict[str, torch.Tensor]:

						"""simple docstring"""






						lowerCAmelCase__					:    List[Any]												=					index + 1  # linecache starts at 1
						lowerCAmelCase__					:    Any												=					self.prefix + linecache.getline(str(self.src_file			)		,__lowerCamelCase			).rstrip('''\n'''			)
						lowerCAmelCase__					:    Any												=					linecache.getline(str(self.tgt_file			)		,__lowerCamelCase			).rstrip('''\n'''			)
						assert source_line, f"""empty source line for index {index}"""
						assert tgt_line, f"""empty tgt line for index {index}"""

						# Need to add eos token manually for T5
						if isinstance(self.tokenizer		,__lowerCamelCase			):
										source_line += self.tokenizer.eos_token
										tgt_line += self.tokenizer.eos_token

						# Pad source and target to the right
						lowerCAmelCase__					:    List[str]												=					(
						    self.tokenizer.question_encoder if isinstance(self.tokenizer		,__lowerCamelCase			) else self.tokenizer
						)
						lowerCAmelCase__					:    Dict												=					self.tokenizer.generator if isinstance(self.tokenizer		,__lowerCamelCase			) else self.tokenizer

						lowerCAmelCase__					:    Union[str, Any]												=					encode_line(__lowerCamelCase		,__lowerCamelCase		,self.max_source_length		,'''right'''			)
						lowerCAmelCase__					:    Any												=					encode_line(__lowerCamelCase		,__lowerCamelCase		,self.max_target_length		,'''right'''			)

						lowerCAmelCase__					:    List[str]												=					source_inputs['''input_ids'''].squeeze()
						lowerCAmelCase__					:    str												=					target_inputs['''input_ids'''].squeeze()
						lowerCAmelCase__					:    Tuple												=					source_inputs['''attention_mask'''].squeeze()
						return {
						    "input_ids": source_ids,
						    "attention_mask": src_mask,
						    "decoder_input_ids": target_ids,
						}



		@staticmethod
		def 		lowerCAmelCase__				(__lowerCamelCase			)					->      List[str]:

						"""simple docstring"""






						return [len(__lowerCamelCase			) for x in Path(__lowerCamelCase			).open().readlines()]



		def 		lowerCAmelCase__				(self		,__lowerCamelCase			)					->      Dict[str, torch.Tensor]:

						"""simple docstring"""






						lowerCAmelCase__					:    Union[str, Any]												=					torch.stack([x['''input_ids'''] for x in batch]			)
						lowerCAmelCase__					:    Union[str, Any]												=					torch.stack([x['''attention_mask'''] for x in batch]			)
						lowerCAmelCase__					:    List[Any]												=					torch.stack([x['''decoder_input_ids'''] for x in batch]			)
						lowerCAmelCase__					:    Any												=					(
						    self.tokenizer.generator.pad_token_id
						    if isinstance(self.tokenizer		,__lowerCamelCase			)
						    else self.tokenizer.pad_token_id
						)
						lowerCAmelCase__					:    Tuple												=					(
						    self.tokenizer.question_encoder.pad_token_id
						    if isinstance(self.tokenizer		,__lowerCamelCase			)
						    else self.tokenizer.pad_token_id
						)
						lowerCAmelCase__					:    Dict												=					trim_batch(__lowerCamelCase		,__lowerCamelCase			)
						lowerCAmelCase__						,		lowerCAmelCase__					:    Union[str, Any]												=					trim_batch(__lowerCamelCase		,__lowerCamelCase		,attention_mask=__lowerCamelCase			)
						lowerCAmelCase__					:    Union[str, Any]												=					{
						    '''input_ids''': source_ids,
						    '''attention_mask''': source_mask,
						    '''decoder_input_ids''': y,
						}
						return batch


__snake_case    :		Any  =getLogger(__name__)






def      lowerCAmelCase__		(   lowerCamelCase_		:		List[List]):





				'''simple docstring'''

				return list(itertools.chain.from_iterable(lowerCamelCase_))






def      lowerCAmelCase__		(   lowerCamelCase_		:		str):





				'''simple docstring'''

				lowerCAmelCase__					:    int												=					get_git_info()
				save_json(lowerCamelCase_	,os.path.join(lowerCamelCase_	,'''git_log.json'''))






def      lowerCAmelCase__		(   lowerCamelCase_		:		Tuple	,lowerCamelCase_		:		Union[str, Any]	,lowerCamelCase_		:		Tuple=4	,**lowerCamelCase_		:		List[str]):





				'''simple docstring'''

				with open(lowerCamelCase_	,'''w''') as f:
								json.dump(lowerCamelCase_	,lowerCamelCase_	,indent=lowerCamelCase_	,**lowerCamelCase_)






def      lowerCAmelCase__		(   lowerCamelCase_		:		Tuple):





				'''simple docstring'''

				with open(lowerCamelCase_) as f:
								return json.load(lowerCamelCase_)






def      lowerCAmelCase__		(   ):





				'''simple docstring'''

				lowerCAmelCase__					:    str												=					git.Repo(search_parent_directories=lowerCamelCase_)
				lowerCAmelCase__					:    List[Any]												=					{
				    '''repo_id''': str(lowerCamelCase_),
				    '''repo_sha''': str(repo.head.object.hexsha),
				    '''repo_branch''': str(repo.active_branch),
				    '''hostname''': str(socket.gethostname()),
				}
				return repo_infos






def      lowerCAmelCase__		(   lowerCamelCase_		:		Callable	,lowerCamelCase_		:		Iterable):





				'''simple docstring'''

				return list(map(lowerCamelCase_	,lowerCamelCase_))






def      lowerCAmelCase__		(   lowerCamelCase_		:		Any	,lowerCamelCase_		:		Optional[Any]):





				'''simple docstring'''

				with open(lowerCamelCase_	,'''wb''') as f:
								return pickle.dump(lowerCamelCase_	,lowerCamelCase_)






def      lowerCAmelCase__		(   lowerCamelCase_		:		int):





				'''simple docstring'''

				def remove_articles(lowerCamelCase_		:		List[str]):
								return re.sub(r'''\b(a|an|the)\b'''	,''' '''	,lowerCamelCase_)

				def white_space_fix(lowerCamelCase_		:		Optional[int]):
								return " ".join(text.split())

				def remove_punc(lowerCamelCase_		:		List[str]):
								lowerCAmelCase__					:    List[Any]												=					set(string.punctuation)
								return "".join(ch for ch in text if ch not in exclude)

				def lower(lowerCamelCase_		:		Optional[int]):
								return text.lower()

				return white_space_fix(remove_articles(remove_punc(lower(lowerCamelCase_))))






def      lowerCAmelCase__		(   lowerCamelCase_		:		List[Any]	,lowerCamelCase_		:		Optional[int]):





				'''simple docstring'''

				lowerCAmelCase__					:    Optional[Any]												=					normalize_answer(lowerCamelCase_).split()
				lowerCAmelCase__					:    str												=					normalize_answer(lowerCamelCase_).split()
				lowerCAmelCase__					:    str												=					Counter(lowerCamelCase_) & Counter(lowerCamelCase_)
				lowerCAmelCase__					:    Dict												=					sum(common.values())
				if num_same == 0:
								return 0
				lowerCAmelCase__					:    Optional[int]												=					1.0 * num_same / len(lowerCamelCase_)
				lowerCAmelCase__					:    Optional[Any]												=					1.0 * num_same / len(lowerCamelCase_)
				lowerCAmelCase__					:    Optional[Any]												=					(2 * precision * recall) / (precision + recall)
				return fa






def      lowerCAmelCase__		(   lowerCamelCase_		:		Union[str, Any]	,lowerCamelCase_		:		Any):





				'''simple docstring'''

				return normalize_answer(lowerCamelCase_) == normalize_answer(lowerCamelCase_)






def      lowerCAmelCase__		(   lowerCamelCase_		:		List[str]	,lowerCamelCase_		:		List[str]):





				'''simple docstring'''

				assert len(lowerCamelCase_) == len(lowerCamelCase_)
				lowerCAmelCase__					:    List[str]												=					0
				for hypo, pred in zip(lowerCamelCase_	,lowerCamelCase_):
								em += exact_match_score(lowerCamelCase_	,lowerCamelCase_)
				if len(lowerCamelCase_) > 0:
								em /= len(lowerCamelCase_)
				return {"em": em}






def      lowerCAmelCase__		(   lowerCamelCase_		:		int):





				'''simple docstring'''

				return model_prefix.startswith('''rag''')






def      lowerCAmelCase__		(   lowerCamelCase_		:		List[str]	,lowerCamelCase_		:		Dict	,lowerCamelCase_		:		str):





				'''simple docstring'''

				lowerCAmelCase__					:    Any												=					{p: p for p in extra_params}
				# T5 models don't have `dropout` param, they have `dropout_rate` instead
				lowerCAmelCase__					:    Optional[int]												=					'''dropout_rate'''
				for p in extra_params:
								if getattr(lowerCamelCase_	,lowerCamelCase_	,lowerCamelCase_):
												if not hasattr(lowerCamelCase_	,lowerCamelCase_) and not hasattr(lowerCamelCase_	,equivalent_param[p]):
																logger.info('''config doesn\'t have a `{}` attribute'''.format(lowerCamelCase_))
																delattr(lowerCamelCase_	,lowerCamelCase_)
																continue
												lowerCAmelCase__					:    Dict												=					p if hasattr(lowerCamelCase_	,lowerCamelCase_) else equivalent_param[p]
												setattr(lowerCamelCase_	,lowerCamelCase_	,getattr(lowerCamelCase_	,lowerCamelCase_))
												delattr(lowerCamelCase_	,lowerCamelCase_)
				return hparams, config

