




"""simple docstring"""







import copy
import fnmatch
import json
import os
import pickle as pkl
import shutil
import sys
import tarfile
import tempfile
from collections import OrderedDict
from contextlib import contextmanager
from functools import partial
from hashlib import shaaaa
from io import BytesIO
from pathlib import Path
from urllib.parse import urlparse
from zipfile import ZipFile, is_zipfile

import cva
import numpy as np
import requests
import wget
from filelock import FileLock
from PIL import Image
from tqdm.auto import tqdm
from yaml import Loader, dump, load


try:
		import torch

		a      =							True
except ImportError:
		a      =							False


try:
		from torch.hub import _get_torch_home

		a      =							_get_torch_home()
except ImportError:
		a      =							os.path.expanduser(
		    os.getenv('TORCH_HOME', os.path.join(os.getenv('XDG_CACHE_HOME', '~/.cache'), 'torch'))
		)

a      =							os.path.join(torch_cache_home, 'transformers')

a      =							'''https://cdn.huggingface.co'''
a      =							'''https://s3.amazonaws.com/models.huggingface.co/bert'''
a      =							'''/'''.join(str(Path(__file__).resolve()).split('/')[:-1])
a      =							os.path.join(PATH, 'config.yaml')
a      =							os.path.join(PATH, 'attributes.txt')
a      =							os.path.join(PATH, 'objects.txt')
a      =							os.getenv('PYTORCH_PRETRAINED_BERT_CACHE', default_cache_path)
a      =							os.getenv('PYTORCH_TRANSFORMERS_CACHE', PYTORCH_PRETRAINED_BERT_CACHE)
a      =							os.getenv('TRANSFORMERS_CACHE', PYTORCH_TRANSFORMERS_CACHE)
a      =							'''pytorch_model.bin'''
a      =							'''config.yaml'''





def 							lowercase					(snake_case__   : List[str]=OBJECTS      ,       snake_case__   : Optional[Any]=ATTRIBUTES )     ->  List[str]:


				'''simple docstring'''






				lowerCAmelCase  =				[]
				with open(snake_case__ ) as f:
								for object in f.readlines():
												vg_classes.append(object.split(""",""" )[0].lower().strip() )

				lowerCAmelCase  =				[]
				with open(snake_case__ ) as f:
								for object in f.readlines():
												vg_attrs.append(object.split(""",""" )[0].lower().strip() )
				return vg_classes, vg_attrs





def 							lowercase					(snake_case__   : int )     ->  Optional[int]:


				'''simple docstring'''






				lowerCAmelCase  =				OrderedDict()
				with open(snake_case__      ,       """rb""" ) as f:
								lowerCAmelCase  =				pkl.load(snake_case__ )['model']
				for k in copy.deepcopy(list(ckp.keys() ) ):
								lowerCAmelCase  =				ckp.pop(snake_case__ )
								if isinstance(snake_case__      ,       np.ndarray ):
												lowerCAmelCase  =				torch.tensor(snake_case__ )
								else:
												assert isinstance(snake_case__      ,       torch.tensor ), type(snake_case__ )
								lowerCAmelCase  =				v
				return r







class       SCREAMING_SNAKE_CASE__					:
						_a    						=						{}


						def __init__(							self				:			List[Any]						,						lowerCAmelCase				:			Union[str, Any]						,						lowerCAmelCase				:			Optional[int] = "root"						,						lowerCAmelCase				:			List[Any]=0					):
										lowerCAmelCase  =				name
										lowerCAmelCase  =				level
										lowerCAmelCase  =				{}
										for k, v in dictionary.items():
														if v is None:
																		raise ValueError()
														lowerCAmelCase  =				copy.deepcopy(_A					)
														lowerCAmelCase  =				copy.deepcopy(_A					)
														if isinstance(_A						,						_A					):
																		lowerCAmelCase  =				Config(_A						,						name=_A						,						level=level + 1					)
														lowerCAmelCase  =				v
														setattr(self						,						_A						,						_A					)

										lowerCAmelCase  =				d


						def __repr__(							self				:			Any					):
										return str(list((self._pointer.keys())					)					)


						def __setattr__(							self				:			Union[str, Any]						,						lowerCAmelCase				:			List[str]						,						lowerCAmelCase				:			int					):
										lowerCAmelCase  =				val
										lowerCAmelCase  =				val
										lowerCAmelCase  =				key.split("""."""					)
										lowerCAmelCase  =				len(_A					) - 1
										lowerCAmelCase  =				self._pointer
										if len(_A					) > 1:
														for i, l in enumerate(_A					):
																		if hasattr(self						,						_A					) and isinstance(getattr(self						,						_A					)						,						_A					):
																						setattr(getattr(self						,						_A					)						,						""".""".join(levels[i:]					)						,						_A					)
																		if l == last_level:
																						lowerCAmelCase  =				val
																		else:
																						lowerCAmelCase  =				pointer[l]


						def   __lowercase (							self				:			Any					):
										return self._pointer


						def   __lowercase (							self				:			Dict						,						lowerCAmelCase				:			Dict						,						lowerCAmelCase				:			Tuple					):
										with open(f'''{file_name}'''						,						"""w"""					) as stream:
														dump(_A						,						_A					)


						def   __lowercase (							self				:			Optional[Any]						,						lowerCAmelCase				:			Tuple						,						lowerCAmelCase				:			int					):
										with open(f'''{file_name}'''						,						"""w"""					) as stream:
														json.dump(_A						,						_A					)


						@staticmethod
						def   __lowercase (							lowerCAmelCase				:			List[str]					):
										with open(_A					) as stream:
														lowerCAmelCase  =				load(_A						,						Loader=_A					)
										return data


						def __str__(							self				:			Union[str, Any]					):
										lowerCAmelCase  =				'    '
										if self._name != "root":
														lowerCAmelCase  =				f'''{t * (self._level-1)}{self._name}:\n'''
										else:
														lowerCAmelCase  =				''
										lowerCAmelCase  =				self._level
										for i, (k, v) in enumerate(self._pointer.items()					):
														if isinstance(_A						,						_A					):
																		r += f'''{t * (self._level)}{v}\n'''
																		self._level += 1
														else:
																		r += f'''{t * (self._level)}{k}: {v} ({type(_A					).__name__})\n'''
														lowerCAmelCase  =				level
										return r[:-1]


						@classmethod
						def   __lowercase (							cls				:			Tuple						,						lowerCAmelCase				:			Dict						,						**lowerCAmelCase				:			List[str]					):
										lowerCAmelCase  =				cls.get_config_dict(_A						,						**_A					)
										return cls(_A					)




						@classmethod
						def   __lowercase (							cls				:			Tuple						,						lowerCAmelCase				:			str						,						**lowerCAmelCase				:			Dict					):
										lowerCAmelCase  =				kwargs.pop("""cache_dir"""						,						_A					)
										lowerCAmelCase  =				kwargs.pop("""force_download"""						,						_A					)
										lowerCAmelCase  =				kwargs.pop("""resume_download"""						,						_A					)
										lowerCAmelCase  =				kwargs.pop("""proxies"""						,						_A					)
										lowerCAmelCase  =				kwargs.pop("""local_files_only"""						,						_A					)

										if os.path.isdir(_A					):
														lowerCAmelCase  =				os.path.join(_A						,						_A					)
										elif os.path.isfile(_A					) or is_remote_url(_A					):
														lowerCAmelCase  =				pretrained_model_name_or_path
										else:
														lowerCAmelCase  =				hf_bucket_url(_A						,						filename=_A						,						use_cdn=_A					)

										try:
														# Load from URL or cache if already cached
														lowerCAmelCase  =				cached_path(
														    _A						,						cache_dir=_A						,						force_download=_A						,						proxies=_A						,						resume_download=_A						,						local_files_only=_A						,						)
														# Load config dict
														if resolved_config_file is None:
																		raise EnvironmentError

														lowerCAmelCase  =				Config.load_yaml(_A					)

										except EnvironmentError:
														lowerCAmelCase  =				'Can\'t load config for'
														raise EnvironmentError(_A					)

										if resolved_config_file == config_file:
														print("""loading configuration file from path"""					)
										else:
														print("""loading configuration file cache"""					)

										return Config.load_yaml(_A					), kwargs





def 							lowercase					(snake_case__   : Dict )     ->  Tuple:


				'''simple docstring'''






				lowerCAmelCase  =				torch.load("""dump.pt"""      ,       map_location=in_tensor.device )
				lowerCAmelCase  =				in_tensor.numpy()
				lowerCAmelCase  =				out_tensor.numpy()[0]
				print(na.shape      ,       na[0, 0, :5] )
				print(na.shape      ,       na[0, 0, :5] )
				assert np.allclose(snake_case__      ,       snake_case__      ,       rtol=0.01      ,       atol=0.1 ), (
				    f'''{sum([1 for x in np.isclose(snake_case__      ,       snake_case__      ,       rtol=0.01      ,       atol=0.1 ).flatten() if x is False] )/len(na.flatten() )*100:.4f} %'''
				    " element-wise mismatch"
				)
				raise Exception("""tensors are all good""" )

				# Hugging face functions below





def 							lowercase					(snake_case__   : List[str] )     ->  str:


				'''simple docstring'''






				lowerCAmelCase  =				urlparse(snake_case__ )
				return parsed.scheme in ("http", "https")





def 							lowercase					(snake_case__   : List[Any]      ,       snake_case__   : Optional[Any]      ,       snake_case__   : Union[str, Any]=True )     ->  str:


				'''simple docstring'''






				lowerCAmelCase  =				CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
				lowerCAmelCase  =				'/' not in model_id
				if legacy_format:
								return f'''{endpoint}/{model_id}-{filename}'''
				else:
								return f'''{endpoint}/{model_id}/{filename}'''





def 							lowercase					(snake_case__   : int      ,       snake_case__   : Union[str, Any]      ,       snake_case__   : Dict=None      ,       snake_case__   : List[str]=0      ,       snake_case__   : Union[str, Any]=None      ,       )     ->  str:


				'''simple docstring'''






				lowerCAmelCase  =				'python/{}'.format(sys.version.split()[0] )
				if _torch_available:
								ua += "; torch/{}".format(torch.__version__ )
				if isinstance(snake_case__      ,       snake_case__ ):
								ua += "; " + "; ".join("""{}/{}""".format(snake_case__      ,       snake_case__ ) for k, v in user_agent.items() )
				elif isinstance(snake_case__      ,       snake_case__ ):
								ua += "; " + user_agent
				lowerCAmelCase  =				{'user-agent': ua}
				if resume_size > 0:
								lowerCAmelCase  =				'bytes=%d-' % (resume_size,)
				lowerCAmelCase  =				requests.get(snake_case__      ,       stream=snake_case__      ,       proxies=snake_case__      ,       headers=snake_case__ )
				if response.status_code == 416:  # Range not satisfiable
								return
				lowerCAmelCase  =				response.headers.get("""Content-Length""" )
				lowerCAmelCase  =				resume_size + int(snake_case__ ) if content_length is not None else None
				lowerCAmelCase  =				tqdm(
				    unit="""B"""      ,       unit_scale=snake_case__      ,       total=snake_case__      ,       initial=snake_case__      ,       desc="""Downloading"""      ,       )
				for chunk in response.iter_content(chunk_size=1_024 ):
								if chunk:  # filter out keep-alive new chunks
												progress.update(len(snake_case__ ) )
												temp_file.write(snake_case__ )
				progress.close()





def 							lowercase					(snake_case__   : Dict      ,       snake_case__   : Optional[int]=None      ,       snake_case__   : List[str]=False      ,       snake_case__   : List[Any]=None      ,       snake_case__   : List[str]=10      ,       snake_case__   : str=False      ,       snake_case__   : Union[str, Any]=None      ,       snake_case__   : List[str]=False      ,       )     ->  Optional[Any]:


				'''simple docstring'''






				if cache_dir is None:
								lowerCAmelCase  =				TRANSFORMERS_CACHE
				if isinstance(snake_case__      ,       snake_case__ ):
								lowerCAmelCase  =				str(snake_case__ )

				os.makedirs(snake_case__      ,       exist_ok=snake_case__ )

				lowerCAmelCase  =				None
				if not local_files_only:
								try:
												lowerCAmelCase  =				requests.head(snake_case__      ,       allow_redirects=snake_case__      ,       proxies=snake_case__      ,       timeout=snake_case__ )
												if response.status_code == 200:
																lowerCAmelCase  =				response.headers.get("""ETag""" )
								except (EnvironmentError, requests.exceptions.Timeout):
												# etag is already None
												pass

				lowerCAmelCase  =				url_to_filename(snake_case__      ,       snake_case__ )

				# get cache path to put the file
				lowerCAmelCase  =				os.path.join(snake_case__      ,       snake_case__ )

				# etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible.
				# try to get the last downloaded one
				if etag is None:
								if os.path.exists(snake_case__ ):
												return cache_path
								else:
												lowerCAmelCase  =				[
												    file
												    for file in fnmatch.filter(os.listdir(snake_case__ )      ,       filename + """.*""" )
												    if not file.endswith(""".json""" ) and not file.endswith(""".lock""" )
												]
												if len(snake_case__ ) > 0:
																return os.path.join(snake_case__      ,       matching_files[-1] )
												else:
																# If files cannot be found and local_files_only=True,
																# the models might've been found if local_files_only=False
																# Notify the user about that
																if local_files_only:
																				raise ValueError(
																				    """Cannot find the requested files in the cached path and outgoing traffic has been"""
																				    """ disabled. To enable model look-ups and downloads online, set \'local_files_only\'"""
																				    """ to False.""" )
																return None

    # From now on, etag is not None.
				if os.path.exists(snake_case__ ) and not force_download:
								return cache_path

				# Prevent parallel downloads of the same file with a lock.
				lowerCAmelCase  =				cache_path + '.lock'
				with FileLock(snake_case__ ):
								# If the download just completed while the lock was activated.
								if os.path.exists(snake_case__ ) and not force_download:
												# Even if returning early like here, the lock will be released.
												return cache_path

								if resume_download:
												lowerCAmelCase  =				cache_path + '.incomplete'

												@contextmanager
												def _resumable_file_manager():
																with open(snake_case__      ,       """a+b""" ) as f:
																				yield f

												lowerCAmelCase  =				_resumable_file_manager
												if os.path.exists(snake_case__ ):
																lowerCAmelCase  =				os.stat(snake_case__ ).st_size
												else:
																lowerCAmelCase  =				0
								else:
												lowerCAmelCase  =				partial(tempfile.NamedTemporaryFile      ,       dir=snake_case__      ,       delete=snake_case__ )
												lowerCAmelCase  =				0

								# Download to temporary file, then copy to cache dir once finished.
								# Otherwise you get corrupt cache entries if the download gets interrupted.
								with temp_file_manager() as temp_file:
												print(
												    """%s not found in cache or force_download set to True, downloading to %s"""      ,       snake_case__      ,       temp_file.name      ,       )

												http_get(
												    snake_case__      ,       snake_case__      ,       proxies=snake_case__      ,       resume_size=snake_case__      ,       user_agent=snake_case__      ,       )

								os.replace(temp_file.name      ,       snake_case__ )

								lowerCAmelCase  =				{'url': url, 'etag': etag}
								lowerCAmelCase  =				cache_path + '.json'
								with open(snake_case__      ,       """w""" ) as meta_file:
												json.dump(snake_case__      ,       snake_case__ )

				return cache_path





def 							lowercase					(snake_case__   : Optional[int]      ,       snake_case__   : Optional[Any]=None )     ->  Optional[Any]:


				'''simple docstring'''






				lowerCAmelCase  =				url.encode("""utf-8""" )
				lowerCAmelCase  =				shaaaa(snake_case__ )
				lowerCAmelCase  =				url_hash.hexdigest()

				if etag:
								lowerCAmelCase  =				etag.encode("""utf-8""" )
								lowerCAmelCase  =				shaaaa(snake_case__ )
								filename += "." + etag_hash.hexdigest()

				if url.endswith(""".h5""" ):
								filename += ".h5"

				return filename





def 							lowercase					(snake_case__   : Dict      ,       snake_case__   : Tuple=None      ,       snake_case__   : Optional[int]=False      ,       snake_case__   : str=None      ,       snake_case__   : Dict=False      ,       snake_case__   : Union[str, Any]=None      ,       snake_case__   : int=False      ,       snake_case__   : Optional[int]=False      ,       snake_case__   : int=False      ,       )     ->  Optional[Any]:


				'''simple docstring'''






				if cache_dir is None:
								lowerCAmelCase  =				TRANSFORMERS_CACHE
				if isinstance(snake_case__      ,       snake_case__ ):
								lowerCAmelCase  =				str(snake_case__ )
				if isinstance(snake_case__      ,       snake_case__ ):
								lowerCAmelCase  =				str(snake_case__ )

				if is_remote_url(snake_case__ ):
								# URL, so get it from the cache (downloading if necessary)
								lowerCAmelCase  =				get_from_cache(
								    snake_case__      ,       cache_dir=snake_case__      ,       force_download=snake_case__      ,       proxies=snake_case__      ,       resume_download=snake_case__      ,       user_agent=snake_case__      ,       local_files_only=snake_case__      ,       )
				elif os.path.exists(snake_case__ ):
								# File, and it exists.
								lowerCAmelCase  =				url_or_filename
				elif urlparse(snake_case__ ).scheme == "":
								# File, but it doesn't exist.
								raise EnvironmentError("""file {} not found""".format(snake_case__ ) )
				else:
								# Something unknown
								raise ValueError("""unable to parse {} as a URL or as a local path""".format(snake_case__ ) )

				if extract_compressed_file:
								if not is_zipfile(snake_case__ ) and not tarfile.is_tarfile(snake_case__ ):
												return output_path

								# Path where we extract compressed archives
								# We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/"
								lowerCAmelCase  =				os.path.split(snake_case__ )
								lowerCAmelCase  =				output_file.replace("""."""      ,       """-""" ) + '-extracted'
								lowerCAmelCase  =				os.path.join(snake_case__      ,       snake_case__ )

								if os.path.isdir(snake_case__ ) and os.listdir(snake_case__ ) and not force_extract:
												return output_path_extracted

								# Prevent parallel extractions
								lowerCAmelCase  =				output_path + '.lock'
								with FileLock(snake_case__ ):
												shutil.rmtree(snake_case__      ,       ignore_errors=snake_case__ )
												os.makedirs(snake_case__ )
												if is_zipfile(snake_case__ ):
																with ZipFile(snake_case__      ,       """r""" ) as zip_file:
																				zip_file.extractall(snake_case__ )
																				zip_file.close()
												elif tarfile.is_tarfile(snake_case__ ):
																lowerCAmelCase  =				tarfile.open(snake_case__ )
																tar_file.extractall(snake_case__ )
																tar_file.close()
												else:
																raise EnvironmentError("""Archive format of {} could not be identified""".format(snake_case__ ) )

								return output_path_extracted

				return output_path





def 							lowercase					(snake_case__   : Tuple      ,       snake_case__   : Union[str, Any]="," )     ->  List[str]:


				'''simple docstring'''






				assert isinstance(snake_case__      ,       snake_case__ )
				if os.path.isfile(snake_case__ ):
								with open(snake_case__ ) as f:
												lowerCAmelCase  =				eval(f.read() )
				else:
								lowerCAmelCase  =				requests.get(snake_case__ )
								try:
												lowerCAmelCase  =				requests.json()
								except Exception:
												lowerCAmelCase  =				req.content.decode()
												assert data is not None, "could not connect"
												try:
																lowerCAmelCase  =				eval(snake_case__ )
												except Exception:
																lowerCAmelCase  =				data.split("""\n""" )
								req.close()
				return data





def 							lowercase					(snake_case__   : Optional[int] )     ->  int:


				'''simple docstring'''






				lowerCAmelCase  =				requests.get(snake_case__ )
				lowerCAmelCase  =				np.array(Image.open(BytesIO(response.content ) ) )
				return img





def 							lowercase					(snake_case__   : List[str] )     ->  Union[str, Any]:


				'''simple docstring'''






				lowerCAmelCase  =				url.split("""/""" )[-1]
				if fn not in os.listdir(os.getcwd() ):
								wget.download(snake_case__ )
				with open(snake_case__      ,       """rb""" ) as stream:
								lowerCAmelCase  =				pkl.load(snake_case__ )
				lowerCAmelCase  =				weights.pop("""model""" )
				lowerCAmelCase  =				{}
				for k, v in model.items():
								lowerCAmelCase  =				torch.from_numpy(snake_case__ )
								if "running_var" in k:
												lowerCAmelCase  =				torch.tensor([0] )
												lowerCAmelCase  =				k.replace("""running_var"""      ,       """num_batches_tracked""" )
												lowerCAmelCase  =				zero
				return new





def 							lowercase					()     ->  List[str]:


				'''simple docstring'''






				print(f'''{os.path.abspath(os.path.join(snake_case__      ,       os.pardir ) )}/demo.ipynb''' )





def 							lowercase					(snake_case__   : int      ,       snake_case__   : Tuple="RGB" )     ->  Tuple:


				'''simple docstring'''






				assert isinstance(snake_case__      ,       snake_case__ )
				if os.path.isfile(snake_case__ ):
								lowerCAmelCase  =				cva.imread(snake_case__ )
				else:
								lowerCAmelCase  =				get_image_from_url(snake_case__ )
								assert img is not None, f'''could not connect to: {im}'''
				lowerCAmelCase  =				cva.cvtColor(snake_case__      ,       cva.COLOR_BGR2RGB )
				if input_format == "RGB":
								lowerCAmelCase  =				img[:, :, ::-1]
				return img






def 							lowercase					(snake_case__   : str      ,       snake_case__   : Optional[int]=1 )     ->  Dict:


				'''simple docstring'''






				return (images[i : i + batch] for i in range(0      ,       len(snake_case__ )      ,       snake_case__ ))











"""simple docstring"""







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


a      =							{
    '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:
		a      =							['OwlViTFeatureExtractor']
		a      =							['OwlViTImageProcessor']

try:
		if not is_torch_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		a      =							[
		    '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

		a      =							_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)





