




'''simple docstring'''

import bza
import gzip
import lzma
import os
import shutil
import struct
import tarfile
import warnings
import zipfile
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Dict, List, Optional, Type, Union

from .. import config
from .filelock import FileLock
from .logging import get_logger


a       :						Dict								=		get_logger(__name__)



class 		SCREAMING_SNAKE_CASE__  :





			def __init__(      self						:    List[Any]      ,		a_						:    Optional[Any] = None							):



						"""simple docstring"""




						__snake_case			=		(
						    os.path.join(A_      ,		config.EXTRACTED_DATASETS_DIR							) if cache_dir else config.EXTRACTED_DATASETS_PATH
						)
						__snake_case			=		Extractor





			def 							A (      self						:    Tuple      ,		a_						:    Optional[Any]							):



						"""simple docstring"""




						from .file_utils import hash_url_to_filename

						# Path where we extract compressed archives
						# We extract in the cache dir, and get the extracted path name by hashing the original path"
						__snake_case			=		os.path.abspath(A_							)
						return os.path.join(self.extract_dir      ,		hash_url_to_filename(A_							)							)





			def 							A (      self						:    Optional[int]      ,		a_						:    Dict      ,		a_						:    Any							):



						"""simple docstring"""




						return force_extract or (
						    not os.path.isfile(A_							) and not (os.path.isdir(A_							) and os.listdir(A_							))
						)






			def 							A (      self						:    Optional[int]      ,		a_						:    str      ,		a_						:    Tuple = False							):



						"""simple docstring"""




						__snake_case			=		self.extractor.infer_extractor_format(A_							)
						if not extractor_format:
									return input_path
						__snake_case			=		self._get_output_path(A_							)
						if self._do_extract(A_      ,		A_							):
									self.extractor.extract(A_      ,		A_      ,		A_							)
						return output_path







class 		SCREAMING_SNAKE_CASE__  (			SCREAMING_SNAKE_CASE__	):





			@classmethod
			@abstractmethod
			def 							A (      cls						:    Dict      ,		a_						:    List[Any]      ,		**a_						:    Optional[int]							):



						"""simple docstring"""




						...






			@staticmethod
			@abstractmethod
			def 							A (      a_						:    Optional[int]      ,		a_						:    str							):



						"""simple docstring"""




						...







class 		SCREAMING_SNAKE_CASE__  (			SCREAMING_SNAKE_CASE__				,     SCREAMING_SNAKE_CASE__	):
			__SCREAMING_SNAKE_CASE    =			[]





			@staticmethod
			def 							A (      a_						:    Optional[Any]      ,		a_						:    int							):



						"""simple docstring"""




						with open(A_      ,		"rb"							) as f:
									return f.read(A_							)






			@classmethod
			def 							A (      cls						:    Any      ,		a_						:    int      ,		a_						:    Optional[Any] = b""							):



						"""simple docstring"""




						if not magic_number:
									__snake_case			=		max(len(A_							) for cls_magic_number in cls.magic_numbers							)
									try:
												__snake_case			=		cls.read_magic_number(A_      ,		A_							)
									except OSError:
												return False
						return any(magic_number.startswith(A_							) for cls_magic_number in cls.magic_numbers							)







class 		SCREAMING_SNAKE_CASE__  (			SCREAMING_SNAKE_CASE__	):





			@classmethod
			def 							A (      cls						:    List[Any]      ,		a_						:    Any      ,		**a_						:    Tuple							):



						"""simple docstring"""




						return tarfile.is_tarfile(A_							)





			@staticmethod
			def 							A (      a_						:    Optional[int]      ,		a_						:    str							):



						"""simple docstring"""




						def resolved(a_						:    List[str]							) -> str:
									return os.path.realpath(os.path.abspath(A_							)							)

						def badpath(a_						:    Union[str, Any]      ,		a_						:    Dict							) -> bool:
									# joinpath will ignore base if path is absolute
									return not resolved(os.path.join(A_      ,		A_							)							).startswith(A_							)

						def badlink(a_						:    Dict      ,		a_						:    Any							) -> bool:
									# Links are interpreted relative to the directory containing the link
									__snake_case			=		resolved(os.path.join(A_      ,		os.path.dirname(info.name							)							)							)
									return badpath(info.linkname      ,		base=A_							)

						__snake_case			=		resolved(A_							)

						for finfo in members:
									if badpath(finfo.name      ,		A_							):
												logger.error(f'''Extraction of {finfo.name} is blocked (illegal path)'''							)
									elif finfo.issym() and badlink(A_      ,		A_							):
												logger.error(f'''Extraction of {finfo.name} is blocked: Symlink to {finfo.linkname}'''							)
									elif finfo.islnk() and badlink(A_      ,		A_							):
												logger.error(f'''Extraction of {finfo.name} is blocked: Hard link to {finfo.linkname}'''							)
									else:
												yield finfo






			@staticmethod
			def 							A (      a_						:    Union[str, Any]      ,		a_						:    Optional[int]							):



						"""simple docstring"""




						os.makedirs(A_      ,		exist_ok=A_							)
						__snake_case			=		tarfile.open(A_							)
						tar_file.extractall(A_      ,		members=TarExtractor.safemembers(A_      ,		A_							)							)
						tar_file.close()







class 		SCREAMING_SNAKE_CASE__  (			SCREAMING_SNAKE_CASE__	):
			__SCREAMING_SNAKE_CASE    =			[B"""\x1F\x8B"""]





			@staticmethod
			def 							A (      a_						:    List[Any]      ,		a_						:    List[Any]							):



						"""simple docstring"""




						with gzip.open(A_      ,		"rb"							) as gzip_file:
									with open(A_      ,		"wb"							) as extracted_file:
												shutil.copyfileobj(A_      ,		A_							)







class 		SCREAMING_SNAKE_CASE__  (			SCREAMING_SNAKE_CASE__	):
			__SCREAMING_SNAKE_CASE    =			[
			    B"""PK\x03\x04""",
			    B"""PK\x05\x06""",  # empty archive
			    B"""PK\x07\x08""",  # spanned archive
			]





			@classmethod
			def 							A (      cls						:    int      ,		a_						:    Any      ,		a_						:    Optional[Any] = b""							):



						"""simple docstring"""




						if super().is_extractable(A_      ,		magic_number=A_							):
									return True
						try:
									# Alternative version of zipfile.is_zipfile that has less false positives, but misses executable zip archives.
									# From: https://github.com/python/cpython/pull/5053
									from zipfile import (
									    _CD_SIGNATURE,
									    _ECD_DISK_NUMBER,
									    _ECD_DISK_START,
									    _ECD_ENTRIES_TOTAL,
									    _ECD_OFFSET,
									    _ECD_SIZE,
									    _EndRecData,
									    sizeCentralDir,
									    stringCentralDir,
									    structCentralDir,
									)

									with open(A_      ,		"rb"							) as fp:
												__snake_case			=		_EndRecData(A_							)
												if endrec:
															if endrec[_ECD_ENTRIES_TOTAL] == 0 and endrec[_ECD_SIZE] == 0 and endrec[_ECD_OFFSET] == 0:
																		return True  # Empty zipfiles are still zipfiles
															elif endrec[_ECD_DISK_NUMBER] == endrec[_ECD_DISK_START]:
																		fp.seek(endrec[_ECD_OFFSET]							)  # Central directory is on the same disk
																		if fp.tell() == endrec[_ECD_OFFSET] and endrec[_ECD_SIZE] >= sizeCentralDir:
																					__snake_case			=		fp.read(A_							)  # CD is where we expect it to be
																					if len(A_							) == sizeCentralDir:
																								__snake_case			=		struct.unpack(A_      ,		A_							)  # CD is the right size
																								if centdir[_CD_SIGNATURE] == stringCentralDir:
																											return True  # First central directory entry  has correct magic number
									return False
						except Exception:  # catch all errors in case future python versions change the zipfile internals
									return False






			@staticmethod
			def 							A (      a_						:    str      ,		a_						:    str							):



						"""simple docstring"""




						os.makedirs(A_      ,		exist_ok=A_							)
						with zipfile.ZipFile(A_      ,		"r"							) as zip_file:
									zip_file.extractall(A_							)
									zip_file.close()







class 		SCREAMING_SNAKE_CASE__  (			SCREAMING_SNAKE_CASE__	):
			__SCREAMING_SNAKE_CASE    =			[B"""\xFD\x37\x7A\x58\x5A\x00"""]





			@staticmethod
			def 							A (      a_						:    Any      ,		a_						:    Dict							):



						"""simple docstring"""




						with lzma.open(A_							) as compressed_file:
									with open(A_      ,		"wb"							) as extracted_file:
												shutil.copyfileobj(A_      ,		A_							)







class 		SCREAMING_SNAKE_CASE__  (			SCREAMING_SNAKE_CASE__	):
			__SCREAMING_SNAKE_CASE    =			[B"""Rar!\x1a\x07\x00""", B"""Rar!\x1a\x07\x01\x00"""]  # RAR_ID  # RAR5_ID





			@staticmethod
			def 							A (      a_						:    Optional[int]      ,		a_						:    Any							):



						"""simple docstring"""




						if not config.RARFILE_AVAILABLE:
									raise ImportError("Please pip install rarfile"							)
						import rarfile

						os.makedirs(A_      ,		exist_ok=A_							)
						__snake_case			=		rarfile.RarFile(A_							)
						rf.extractall(A_							)
						rf.close()







class 		SCREAMING_SNAKE_CASE__  (			SCREAMING_SNAKE_CASE__	):
			__SCREAMING_SNAKE_CASE    =			[B"""\x28\xb5\x2F\xFD"""]





			@staticmethod
			def 							A (      a_						:    Union[str, Any]      ,		a_						:    Optional[Any]							):



						"""simple docstring"""




						if not config.ZSTANDARD_AVAILABLE:
									raise ImportError("Please pip install zstandard"							)
						import zstandard as zstd

						__snake_case			=		zstd.ZstdDecompressor()
						with open(A_      ,		"rb"							) as ifh, open(A_      ,		"wb"							) as ofh:
									dctx.copy_stream(A_      ,		A_							)







class 		SCREAMING_SNAKE_CASE__  (			SCREAMING_SNAKE_CASE__	):
			__SCREAMING_SNAKE_CASE    =			[B"""\x42\x5A\x68"""]





			@staticmethod
			def 							A (      a_						:    str      ,		a_						:    List[Any]							):



						"""simple docstring"""




						with bza.open(A_      ,		"rb"							) as compressed_file:
									with open(A_      ,		"wb"							) as extracted_file:
												shutil.copyfileobj(A_      ,		A_							)







class 		SCREAMING_SNAKE_CASE__  (			SCREAMING_SNAKE_CASE__	):
			__SCREAMING_SNAKE_CASE    =			[B"""\x37\x7A\xBC\xAF\x27\x1C"""]





			@staticmethod
			def 							A (      a_						:    Tuple      ,		a_						:    List[str]							):



						"""simple docstring"""




						if not config.PY7ZR_AVAILABLE:
									raise ImportError("Please pip install py7zr"							)
						import pyazr

						os.makedirs(A_      ,		exist_ok=A_							)
						with pyazr.SevenZipFile(A_      ,		"r"							) as archive:
									archive.extractall(A_							)







class 		SCREAMING_SNAKE_CASE__  (			SCREAMING_SNAKE_CASE__	):
			__SCREAMING_SNAKE_CASE    =			[B"""\x04\x22\x4D\x18"""]





			@staticmethod
			def 							A (      a_						:    Optional[Any]      ,		a_						:    List[Any]							):



						"""simple docstring"""




						if not config.LZ4_AVAILABLE:
									raise ImportError("Please pip install lz4"							)
						import lza.frame

						with lza.frame.open(A_      ,		"rb"							) as compressed_file:
									with open(A_      ,		"wb"							) as extracted_file:
												shutil.copyfileobj(A_      ,		A_							)







class 		SCREAMING_SNAKE_CASE__  :
			#  Put zip file to the last, b/c it is possible wrongly detected as zip (I guess it means: as tar or gzip)
			__SCREAMING_SNAKE_CASE    =			{
			    """tar""": TarExtractor,
			    """gzip""": GzipExtractor,
			    """zip""": ZipExtractor,
			    """xz""": XzExtractor,
			    """rar""": RarExtractor,
			    """zstd""": ZstdExtractor,
			    """bz2""": BzipaExtractor,
			    """7z""": SevenZipExtractor,  # <Added version="2.4.0"/>
			    """lz4""": LzaExtractor,  # <Added version="2.4.0"/>
			}





			@classmethod
			def 							A (      cls						:    str							):



						"""simple docstring"""




						return max(
						    len(A_							)
						    for extractor in cls.extractors.values()
						    if issubclass(A_      ,		A_							)
						    for extractor_magic_number in extractor.magic_numbers							)





			@staticmethod
			def 							A (      a_						:    Dict      ,		a_						:    Optional[int]							):



						"""simple docstring"""




						try:
									return MagicNumberBaseExtractor.read_magic_number(A_      ,		magic_number_length=A_							)
						except OSError:
									return b""





			@classmethod
			def 							A (      cls						:    Optional[Any]      ,		a_						:    str      ,		a_						:    Tuple = False							):



						"""simple docstring"""




						warnings.warn(
						    "Method \'is_extractable\' was deprecated in version 2.4.0 and will be removed in 3.0.0. "
						    "Use \'infer_extractor_format\' instead."      ,		category=A_      ,		)
						__snake_case			=		cls.infer_extractor_format(A_							)
						if extractor_format:
									return True if not return_extractor else (True, cls.extractors[extractor_format])
						return False if not return_extractor else (False, None)





			@classmethod
			def 							A (      cls						:    Union[str, Any]      ,		a_						:    Dict							):  # <Added version="2.4.0"/>



						"""simple docstring"""




						__snake_case			=		cls._get_magic_number_max_length()
						__snake_case			=		cls._read_magic_number(A_      ,		A_							)
						for extractor_format, extractor in cls.extractors.items():
									if extractor.is_extractable(A_      ,		magic_number=A_							):
												return extractor_format






			@classmethod
			def 							A (      cls						:    Tuple      ,		a_						:    int      ,		a_						:    Optional[int]      ,		a_						:    int = None      ,		a_						:    List[Any] = "deprecated"      ,		):



						"""simple docstring"""




						os.makedirs(os.path.dirname(A_							)      ,		exist_ok=A_							)
						# Prevent parallel extractions
						__snake_case			=		str(Path(A_							).with_suffix(".lock"							)							)
						with FileLock(A_							):
									shutil.rmtree(A_      ,		ignore_errors=A_							)
									if extractor_format or extractor != "deprecated":
												if extractor != "deprecated" or not isinstance(A_      ,		A_							):  # passed as positional arg
															warnings.warn(
															    "Parameter \'extractor\' was deprecated in version 2.4.0 and will be removed in 3.0.0. "
															    "Use \'extractor_format\' instead."      ,		category=A_      ,		)
															__snake_case			=		extractor if extractor != '''deprecated''' else extractor_format
												else:
															__snake_case			=		cls.extractors[extractor_format]
												return extractor.extract(A_      ,		A_							)
									else:
												warnings.warn(
												    "Parameter \'extractor_format\' was made required in version 2.4.0 and not passing it will raise an "
												    "exception in 3.0.0."      ,		category=A_      ,		)
												for extractor in cls.extractors.values():
															if extractor.is_extractable(A_							):
																		return extractor.extract(A_      ,		A_							)







"""simple docstring"""




import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
from ...utils import logging
from ..auto import CONFIG_MAPPING


A__ :       List[Any]				= logging.get_logger(__name__)

A__ :       Tuple				= {
    'Salesforce/instruct-blip-flan-t5': 'https://huggingface.co/Salesforce/instruct-blip-flan-t5/resolve/main/config.json',
}


class       __magic_name__							(							SCREAMING_SNAKE_CASE__			):
       UpperCamelCase_ =		'''instructblip_vision_model'''
       def __init__(  self			,					A_=1408			,					A_=6144			,					A_=39			,					A_=16			,					A_=224			,					A_=14			,					A_="gelu"			,					A_=1E-6			,					A_=0.0			,					A_=1E-10			,					A_=True			,					**A_			,					)  ->						Tuple:





         """simple docstring"""




         super().__init__(**A_							)

         _lowercase:      List[str]   			=  hidden_size
         _lowercase:      Tuple   			=  intermediate_size
         _lowercase:      List[str]   			=  num_hidden_layers
         _lowercase:      Union[str, Any]   			=  num_attention_heads
         _lowercase:      str   			=  patch_size
         _lowercase:      Union[str, Any]   			=  image_size
         _lowercase:      int   			=  initializer_range
         _lowercase:      List[str]   			=  attention_dropout
         _lowercase:      Tuple   			=  layer_norm_eps
         _lowercase:      Tuple   			=  hidden_act
         _lowercase:      Optional[int]   			=  qkv_bias



       @classmethod
       def 				lowercase_				(  cls			,					A_			,					**A_							)  ->						"PretrainedConfig":





         """simple docstring"""




         cls._set_token_in_kwargs(A_							)

         _lowercase			,					_lowercase:      str   			=  cls.get_config_dict(A_			,					**A_							)

         # get the vision config dict if we are loading from InstructBlipConfig
         if config_dict.get('''model_type'''							) == "instructblip":
           _lowercase:      Dict   			=  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(A_			,					**A_							)


class       __magic_name__							(							SCREAMING_SNAKE_CASE__			):
       UpperCamelCase_ =		'''instructblip_qformer'''
       def __init__(  self			,					A_=3_0522			,					A_=768			,					A_=12			,					A_=12			,					A_=3072			,					A_="gelu"			,					A_=0.1			,					A_=0.1			,					A_=512			,					A_=0.02			,					A_=1E-12			,					A_=0			,					A_="absolute"			,					A_=2			,					A_=1408			,					**A_			,					)  ->						Optional[int]:





         """simple docstring"""




         super().__init__(pad_token_id=A_			,					**A_							)

         _lowercase:      Optional[Any]   			=  vocab_size
         _lowercase:      Optional[int]   			=  hidden_size
         _lowercase:      Dict   			=  num_hidden_layers
         _lowercase:      Union[str, Any]   			=  num_attention_heads
         _lowercase:      List[Any]   			=  hidden_act
         _lowercase:      Union[str, Any]   			=  intermediate_size
         _lowercase:      Union[str, Any]   			=  hidden_dropout_prob
         _lowercase:      Tuple   			=  attention_probs_dropout_prob
         _lowercase:      Optional[int]   			=  max_position_embeddings
         _lowercase:      Optional[int]   			=  initializer_range
         _lowercase:      Optional[Any]   			=  layer_norm_eps
         _lowercase:      Optional[Any]   			=  position_embedding_type
         _lowercase:      Tuple   			=  cross_attention_frequency
         _lowercase:      str   			=  encoder_hidden_size



       @classmethod
       def 				lowercase_				(  cls			,					A_			,					**A_							)  ->						"PretrainedConfig":





         """simple docstring"""




         cls._set_token_in_kwargs(A_							)

         _lowercase			,					_lowercase:      Tuple   			=  cls.get_config_dict(A_			,					**A_							)

         # get the qformer config dict if we are loading from InstructBlipConfig
         if config_dict.get('''model_type'''							) == "instructblip":
           _lowercase:      Tuple   			=  config_dict['''qformer_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(A_			,					**A_							)


class       __magic_name__							(							SCREAMING_SNAKE_CASE__			):
       UpperCamelCase_ =		'''instructblip'''
       UpperCamelCase_ =		True
       def __init__(  self			,					A_=None			,					A_=None			,					A_=None			,					A_=32			,					**A_							)  ->						str:





         """simple docstring"""




         super().__init__(**A_							)

         if vision_config is None:
           _lowercase:      str   			=  {}
           logger.info('''vision_config is None. initializing the InstructBlipVisionConfig with default values.'''							)

         if qformer_config is None:
           _lowercase:      List[str]   			=  {}
           logger.info('''qformer_config is None. Initializing the InstructBlipQFormerConfig with default values.'''							)

         if text_config is None:
           _lowercase:      Any   			=  {}
           logger.info('''text_config is None. Initializing the text config with default values (`OPTConfig`).'''							)

         _lowercase:      int   			=  InstructBlipVisionConfig(**A_							)
         _lowercase:      Optional[Any]   			=  InstructBlipQFormerConfig(**A_							)
         _lowercase:      Optional[Any]   			=  text_config['''model_type'''] if '''model_type''' in text_config else '''opt'''
         _lowercase:      Optional[Any]   			=  CONFIG_MAPPING[text_model_type](**A_							)

         _lowercase:      Tuple   			=  self.text_config.tie_word_embeddings
         _lowercase:      Dict   			=  self.text_config.is_encoder_decoder

         _lowercase:      List[Any]   			=  num_query_tokens
         _lowercase:      Any   			=  self.vision_config.hidden_size
         _lowercase:      List[Any]   			=  self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
         _lowercase:      Union[str, Any]   			=  1.0
         _lowercase:      Dict   			=  0.02
       @classmethod
       def 				lowercase_				(  cls			,					A_			,					A_			,					A_			,					**A_			,					)  ->						str:





         """simple docstring"""




         return cls(
             vision_config=vision_config.to_dict()			,					qformer_config=qformer_config.to_dict()			,					text_config=text_config.to_dict()			,					**A_			,					)



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





         """simple docstring"""




         _lowercase:      List[str]   			=  copy.deepcopy(self.__dict__							)
         _lowercase:      Tuple   			=  self.vision_config.to_dict()
         _lowercase:      Tuple   			=  self.qformer_config.to_dict()
         _lowercase:      int   			=  self.text_config.to_dict()
         _lowercase:      Any   			=  self.__class__.model_type
         return output
