


'''simple docstring'''



import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


__A		=logging.get_logger(__name__)

__A		={
    'BAAI/AltCLIP': 'https://huggingface.co/BAAI/AltCLIP/resolve/main/config.json',
    # See all AltCLIP models at https://huggingface.co/models?filter=altclip
}


class 						_snake_case   (       a__		):
					lowerCAmelCase :Optional[int]						=   '''altclip_text_model'''




					def __init__( self							,							_lowerCamelCase=25_0002							,							_lowerCamelCase=1024							,							_lowerCamelCase=24							,							_lowerCamelCase=16							,							_lowerCamelCase=4096							,							_lowerCamelCase="gelu"							,							_lowerCamelCase=0.1							,							_lowerCamelCase=0.1							,							_lowerCamelCase=514							,							_lowerCamelCase=1							,							_lowerCamelCase=0.02							,							_lowerCamelCase=0.02							,							_lowerCamelCase=1e-0_5							,							_lowerCamelCase=1							,							_lowerCamelCase=0							,							_lowerCamelCase=2							,							_lowerCamelCase="absolute"							,							_lowerCamelCase=True							,							_lowerCamelCase=768							,							**_lowerCamelCase							,							):
								super().__init__(pad_token_id=_lowerCamelCase							,							bos_token_id=_lowerCamelCase							,							eos_token_id=_lowerCamelCase							,							**_lowerCamelCase)

								UpperCAmelCase__					:   int       				=       vocab_size
								UpperCAmelCase__					:   List[str]       				=       hidden_size
								UpperCAmelCase__					:   List[Any]       				=       num_hidden_layers
								UpperCAmelCase__					:   str       				=       num_attention_heads
								UpperCAmelCase__					:   Tuple       				=       hidden_act
								UpperCAmelCase__					:   Tuple       				=       intermediate_size
								UpperCAmelCase__					:   List[str]       				=       hidden_dropout_prob
								UpperCAmelCase__					:   str       				=       attention_probs_dropout_prob
								UpperCAmelCase__					:   List[Any]       				=       max_position_embeddings
								UpperCAmelCase__					:   List[Any]       				=       type_vocab_size
								UpperCAmelCase__					:   str       				=       initializer_range
								UpperCAmelCase__					:   List[Any]       				=       initializer_factor
								UpperCAmelCase__					:   Optional[Any]       				=       layer_norm_eps
								UpperCAmelCase__					:   List[str]       				=       position_embedding_type
								UpperCAmelCase__					:   Any       				=       use_cache
								UpperCAmelCase__					:   Tuple       				=       project_dim


class 						_snake_case   (       a__		):
					lowerCAmelCase :Optional[int]						=   '''altclip_vision_model'''




					def __init__( self							,							_lowerCamelCase=768							,							_lowerCamelCase=3072							,							_lowerCamelCase=512							,							_lowerCamelCase=12							,							_lowerCamelCase=12							,							_lowerCamelCase=3							,							_lowerCamelCase=224							,							_lowerCamelCase=32							,							_lowerCamelCase="quick_gelu"							,							_lowerCamelCase=1e-5							,							_lowerCamelCase=0.0							,							_lowerCamelCase=0.02							,							_lowerCamelCase=1.0							,							**_lowerCamelCase							,							):
								super().__init__(**_lowerCamelCase)

								UpperCAmelCase__					:   Tuple       				=       hidden_size
								UpperCAmelCase__					:   Any       				=       intermediate_size
								UpperCAmelCase__					:   Optional[int]       				=       projection_dim
								UpperCAmelCase__					:   Optional[int]       				=       num_hidden_layers
								UpperCAmelCase__					:   List[Any]       				=       num_attention_heads
								UpperCAmelCase__					:   Tuple       				=       num_channels
								UpperCAmelCase__					:   Tuple       				=       patch_size
								UpperCAmelCase__					:   str       				=       image_size
								UpperCAmelCase__					:   int       				=       initializer_range
								UpperCAmelCase__					:   List[str]       				=       initializer_factor
								UpperCAmelCase__					:   List[str]       				=       attention_dropout
								UpperCAmelCase__					:   str       				=       layer_norm_eps
								UpperCAmelCase__					:   str       				=       hidden_act




					@classmethod
					def 			snake_case__  ( cls							,							_lowerCamelCase							,							**_lowerCamelCase):
								cls._set_token_in_kwargs(_lowerCamelCase)

								UpperCAmelCase__				,    UpperCAmelCase__					:   Tuple       				=       cls.get_config_dict(_lowerCamelCase							,							**_lowerCamelCase)

								# get the vision config dict if we are loading from AltCLIPConfig
								if config_dict.get("""model_type""") == "altclip":
											UpperCAmelCase__					:   Optional[Any]       				=       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 						_snake_case   (       a__		):
					lowerCAmelCase :List[str]						=   '''altclip'''
					lowerCAmelCase :str						=   True




					def __init__( self							,							_lowerCamelCase=None							,							_lowerCamelCase=None							,							_lowerCamelCase=768							,							_lowerCamelCase=2.6592							,							**_lowerCamelCase):
								# If `_config_dict` exist, we use them for the backward compatibility.
								# We pop out these 2 attributes before calling `super().__init__` to avoid them being saved (which causes a lot
								# of confusion!).
								UpperCAmelCase__					:   List[Any]       				=       kwargs.pop("""text_config_dict"""							,							_lowerCamelCase)
								UpperCAmelCase__					:   Optional[int]       				=       kwargs.pop("""vision_config_dict"""							,							_lowerCamelCase)

								super().__init__(**_lowerCamelCase)

								# Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
								# `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
								# cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
								if text_config_dict is not None:
											if text_config is None:
														UpperCAmelCase__					:   Tuple       				=       {}

											# This is the complete result when using `text_config_dict`.
											UpperCAmelCase__					:   Union[str, Any]       				=       AltCLIPTextConfig(**_lowerCamelCase).to_dict()

											# Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
											for key, value in _text_config_dict.items():
														if key in text_config and value != text_config[key] and key not in ["transformers_version"]:
																	# If specified in `text_config_dict`
																	if key in text_config_dict:
																				UpperCAmelCase__					:   List[Any]       				=       (
																				    f'''`{key}` is found in both `text_config_dict` and `text_config` but with different values. '''
																				    f'''The value `text_config_dict["{key}"]` will be used instead.'''
																				)
																	# If inferred from default argument values (just to be super careful)
																	else:
																				UpperCAmelCase__					:   List[str]       				=       (
																				    f'''`text_config_dict` is provided which will be used to initialize `AltCLIPTextConfig`. The '''
																				    f'''value `text_config["{key}"]` will be overriden.'''
																				)
																	logger.warning(_lowerCamelCase)

            # Update all values in `text_config` with the ones in `_text_config_dict`.
											text_config.update(_text_config_dict)

								if vision_config_dict is not None:
											if vision_config is None:
														UpperCAmelCase__					:   Tuple       				=       {}

											# This is the complete result when using `vision_config_dict`.
											UpperCAmelCase__					:   List[Any]       				=       AltCLIPVisionConfig(**_lowerCamelCase).to_dict()
											# convert keys to string instead of integer
											if "id2label" in _vision_config_dict:
														UpperCAmelCase__					:   Union[str, Any]       				=       {
														    str(_lowerCamelCase): value for key, value in _vision_config_dict["""id2label"""].items()
														}

											# Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
											for key, value in _vision_config_dict.items():
														if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]:
																	# If specified in `vision_config_dict`
																	if key in vision_config_dict:
																				UpperCAmelCase__					:   Optional[int]       				=       (
																				    f'''`{key}` is found in both `vision_config_dict` and `vision_config` but with different '''
																				    f'''values. The value `vision_config_dict["{key}"]` will be used instead.'''
																				)
																	# If inferred from default argument values (just to be super careful)
																	else:
																				UpperCAmelCase__					:   Dict       				=       (
																				    f'''`vision_config_dict` is provided which will be used to initialize `AltCLIPVisionConfig`. '''
																				    f'''The value `vision_config["{key}"]` will be overriden.'''
																				)
																	logger.warning(_lowerCamelCase)

            # Update all values in `vision_config` with the ones in `_vision_config_dict`.
											vision_config.update(_vision_config_dict)

								if text_config is None:
											UpperCAmelCase__					:   Optional[int]       				=       {}
											logger.info("""`text_config` is `None`. Initializing the `AltCLIPTextConfig` with default values.""")

								if vision_config is None:
											UpperCAmelCase__					:   Dict       				=       {}
											logger.info("""`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values.""")

								UpperCAmelCase__					:   Dict       				=       AltCLIPTextConfig(**_lowerCamelCase)
								UpperCAmelCase__					:   Tuple       				=       AltCLIPVisionConfig(**_lowerCamelCase)

								UpperCAmelCase__					:   Optional[Any]       				=       projection_dim
								UpperCAmelCase__					:   Optional[Any]       				=       logit_scale_init_value
								UpperCAmelCase__					:   int       				=       1.0




					@classmethod
					def 			snake_case__  ( cls							,							_lowerCamelCase							,							_lowerCamelCase							,							**_lowerCamelCase):
								return cls(text_config=text_config.to_dict()							,							vision_config=vision_config.to_dict()							,							**_lowerCamelCase)




					def 			snake_case__  ( self):
								UpperCAmelCase__					:   Tuple       				=       copy.deepcopy(self.__dict__)
								UpperCAmelCase__					:   List[Any]       				=       self.text_config.to_dict()
								UpperCAmelCase__					:   List[str]       				=       self.vision_config.to_dict()
								UpperCAmelCase__					:   List[str]       				=       self.__class__.model_type
								return output



'''simple docstring'''



import os
from typing import Optional

import fsspec
from fsspec.archive import AbstractArchiveFileSystem
from fsspec.utils import DEFAULT_BLOCK_SIZE


class 						_snake_case   (       a__		):
					lowerCAmelCase :Optional[int]						=   ''''''
					lowerCAmelCase :str						=   (
					    None  # protocol passed in prefix to the url. ex: "gzip", for gzip://file.txt::http://foo.bar/file.txt.gz
					)
					lowerCAmelCase :str						=   None  # compression type in fsspec. ex: "gzip"
					lowerCAmelCase :str						=   None  # extension of the filename to strip. ex: "".gz" to get file.txt from file.txt.gz




					def __init__( self							,							_lowerCamelCase = ""							,							_lowerCamelCase = None							,							_lowerCamelCase = None							,							**_lowerCamelCase):
								super().__init__(self							,							**_lowerCamelCase)
								# always open as "rb" since fsspec can then use the TextIOWrapper to make it work for "r" mode
								UpperCAmelCase__					:   Optional[Any]       				=       fsspec.open(
								    _lowerCamelCase							,							mode="""rb"""							,							protocol=_lowerCamelCase							,							compression=self.compression							,							client_kwargs={
								        """requote_redirect_url""": False,  # see https://github.com/huggingface/datasets/pull/5459
								        """trust_env""": True,  # Enable reading proxy env variables.
								        **(target_options or {}).pop("""client_kwargs"""							,							{}),  # To avoid issues if it was already passed.
								    }							,							**(target_options or {})							,							)
								UpperCAmelCase__					:   List[Any]       				=       os.path.basename(self.file.path.split("""::""")[0])
								UpperCAmelCase__					:   Dict       				=       (
								    self.compressed_name[: self.compressed_name.rindex(""".""")]
								    if """.""" in self.compressed_name
								    else self.compressed_name
								)
								UpperCAmelCase__					:   Tuple       				=       None




					@classmethod
					def 			snake_case__  ( cls							,							_lowerCamelCase):
								# compressed file paths are always relative to the archive root
								return super()._strip_protocol(_lowerCamelCase).lstrip("""/""")




					def 			snake_case__  ( self):
								if self.dir_cache is None:
											UpperCAmelCase__					:   Optional[Any]       				=       {**self.file.fs.info(self.file.path), """name""": self.uncompressed_name}
											UpperCAmelCase__					:   Union[str, Any]       				=       {f["""name"""]: f}




					def 			snake_case__  ( self							,							_lowerCamelCase):
								return self.file.open().read()




					def 			snake_case__  ( self							,							_lowerCamelCase							,							_lowerCamelCase = "rb"							,							_lowerCamelCase=None							,							_lowerCamelCase=True							,							_lowerCamelCase=None							,							**_lowerCamelCase							,							):
								UpperCAmelCase__					:   List[str]       				=       self._strip_protocol(_lowerCamelCase)
								if mode != "rb":
											raise ValueError(f'''Tried to read with mode {mode} on file {self.file.path} opened with mode \'rb\'''')
								return self.file.open()


class 						_snake_case   (       a__		):
					lowerCAmelCase :Dict						=   '''bz2'''
					lowerCAmelCase :List[str]						=   '''bz2'''
					lowerCAmelCase :Dict						=   '''.bz2'''


class 						_snake_case   (       a__		):
					lowerCAmelCase :int						=   '''gzip'''
					lowerCAmelCase :Tuple						=   '''gzip'''
					lowerCAmelCase :str						=   '''.gz'''


class 						_snake_case   (       a__		):
					lowerCAmelCase :List[str]						=   '''lz4'''
					lowerCAmelCase :Any						=   '''lz4'''
					lowerCAmelCase :int						=   '''.lz4'''


class 						_snake_case   (       a__		):
					lowerCAmelCase :Union[str, Any]						=   '''xz'''
					lowerCAmelCase :int						=   '''xz'''
					lowerCAmelCase :List[Any]						=   '''.xz'''


class 						_snake_case   (       a__		):
					lowerCAmelCase :Tuple						=   '''zstd'''
					lowerCAmelCase :List[str]						=   '''zstd'''
					lowerCAmelCase :Union[str, Any]						=   '''.zst'''




					def __init__( self							,							_lowerCamelCase							,							_lowerCamelCase = "rb"							,							_lowerCamelCase = None							,							_lowerCamelCase = None							,							_lowerCamelCase = DEFAULT_BLOCK_SIZE							,							**_lowerCamelCase							,							):
								super().__init__(
								    fo=_lowerCamelCase							,							mode=_lowerCamelCase							,							target_protocol=_lowerCamelCase							,							target_options=_lowerCamelCase							,							block_size=_lowerCamelCase							,							**_lowerCamelCase							,							)
								# We need to wrap the zstd decompressor to avoid this error in fsspec==2021.7.0 and zstandard==0.15.2:
								#
								# File "/Users/user/.virtualenvs/hf-datasets/lib/python3.7/site-packages/fsspec/core.py", line 145, in open
								#     out.close = close
								# AttributeError: 'zstd.ZstdDecompressionReader' object attribute 'close' is read-only
								#
								# see https://github.com/intake/filesystem_spec/issues/725
								UpperCAmelCase__					:   Dict       				=       self.file.__enter__


								class 						_snake_case   :




													def __init__( self							,							_lowerCamelCase):
																UpperCAmelCase__					:   Optional[int]       				=       file_




													def __enter__( self):
																self._file.__enter__()
																return self




													def __exit__( self							,							*_lowerCamelCase							,							**_lowerCamelCase):
																self._file.__exit__(*_lowerCamelCase							,							**_lowerCamelCase)




													def __iter__( self):
																return iter(self._file)




													def 			snake_case__  ( self):
																return next(self._file)




													def __getattr__( self							,							_lowerCamelCase):
																return getattr(self._file							,							_lowerCamelCase)

								def fixed_enter(*_lowerCamelCase							,							**_lowerCamelCase):
											return WrappedFile(_enter(*_lowerCamelCase							,							**_lowerCamelCase))

								UpperCAmelCase__					:   List[Any]       				=       fixed_enter