


import copy
import os
from typing import Union

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


SCREAMING_SNAKE_CASE :   Optional[Any]							      =				logging.get_logger(__name__)

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






class _lowerCamelCase(		_a     ):
       lowercase_				:			Any									=    """altclip_text_model"""
       def __init__(      self,   lowerCamelCase=25_00_02,   lowerCamelCase=10_24,   lowerCamelCase=24,   lowerCamelCase=16,   lowerCamelCase=40_96,   lowerCamelCase="gelu",   lowerCamelCase=0.1,   lowerCamelCase=0.1,   lowerCamelCase=5_14,   lowerCamelCase=1,   lowerCamelCase=0.0_2,   lowerCamelCase=0.0_2,   lowerCamelCase=1E-05,   lowerCamelCase=1,   lowerCamelCase=0,   lowerCamelCase=2,   lowerCamelCase="absolute",   lowerCamelCase=True,   lowerCamelCase=7_68,   **lowerCamelCase,   ) ->     int:




           """simple docstring"""

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

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






class _lowerCamelCase(		_a     ):
       lowercase_				:			Union[str, Any]									=    """altclip_vision_model"""
       def __init__(      self,   lowerCamelCase=7_68,   lowerCamelCase=30_72,   lowerCamelCase=5_12,   lowerCamelCase=12,   lowerCamelCase=12,   lowerCamelCase=3,   lowerCamelCase=2_24,   lowerCamelCase=32,   lowerCamelCase="quick_gelu",   lowerCamelCase=1E-5,   lowerCamelCase=0.0,   lowerCamelCase=0.0_2,   lowerCamelCase=1.0,   **lowerCamelCase,   ) ->     Union[str, Any]:




           """simple docstring"""

           super().__init__(**lowerCamelCase)

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




       @classmethod
       def     UpperCamelCase  (      cls,   lowerCamelCase,   **lowerCamelCase) ->     "PretrainedConfig":




           """simple docstring"""

           cls._set_token_in_kwargs(lowerCamelCase)

           _lowercase	,       _lowercase :							Optional[int]   	=	cls.get_config_dict(lowerCamelCase,   **lowerCamelCase)

           # get the vision config dict if we are loading from AltCLIPConfig
           if config_dict.get('model_type') == "altclip":
               _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(lowerCamelCase,   **lowerCamelCase)






class _lowerCamelCase(		_a     ):
       lowercase_				:			Tuple									=    """altclip"""
       lowercase_				:			Optional[Any]									=    True
       def __init__(      self,   lowerCamelCase=None,   lowerCamelCase=None,   lowerCamelCase=7_68,   lowerCamelCase=2.6_5_9_2,   **lowerCamelCase) ->     Any:




           """simple docstring"""

           _lowercase :							Tuple   	=	kwargs.pop('text_config_dict',   lowerCamelCase)
           _lowercase :							Any   	=	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:
                   _lowercase :							List[Any]   	=	{}

               # This is the complete result when using `text_config_dict`.
               _lowercase :							Dict   	=	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:
                           _lowercase :							Union[str, 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:
                           _lowercase :							Any   	=	(
                               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:
                   _lowercase :							Tuple   	=	{}

               # This is the complete result when using `vision_config_dict`.
               _lowercase :							Any   	=	AltCLIPVisionConfig(**lowerCamelCase).to_dict()
               # convert keys to string instead of integer
               if "id2label" in _vision_config_dict:
                   _lowercase :							List[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:
                           _lowercase :							Union[str, Any]   	=	(
                               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:
                           _lowercase :							Union[str, Any]   	=	(
                               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:
               _lowercase :							Optional[Any]   	=	{}
               logger.info('`text_config` is `None`. Initializing the `AltCLIPTextConfig` with default values.')

           if vision_config is None:
               _lowercase :							Union[str, Any]   	=	{}
               logger.info('`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values.')

           _lowercase :							Tuple   	=	AltCLIPTextConfig(**lowerCamelCase)
           _lowercase :							Any   	=	AltCLIPVisionConfig(**lowerCamelCase)

           _lowercase :							Optional[Any]   	=	projection_dim
           _lowercase :							int   	=	logit_scale_init_value
           _lowercase :							List[Any]   	=	1.0
       @classmethod
       def     UpperCamelCase  (      cls,   lowerCamelCase,   lowerCamelCase,   **lowerCamelCase) ->     List[str]:




           """simple docstring"""

           return cls(text_config=text_config.to_dict(),   vision_config=vision_config.to_dict(),   **lowerCamelCase)




       def     UpperCamelCase  (      self) ->     str:




           """simple docstring"""

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






import unittest

from transformers.testing_utils import require_bsa
from transformers.utils import is_bsa_available

from ...test_feature_extraction_common import FeatureExtractionSavingTestMixin


if is_bsa_available():
 from transformers import MarkupLMFeatureExtractor






class _lowerCamelCase(		unittest.TestCase     ):
       def __init__(      self,   lowerCamelCase) ->     List[str]:




           """simple docstring"""

           _lowercase :							Optional[int]   	=	parent




       def     UpperCamelCase  (      self) ->     str:




           """simple docstring"""

           return {}



def        UpperCamelCase_(   )					->		List[str]:
    _lowercase :							int   	=	'<HTML>\n\n    <HEAD>\n    <TITLE>sample document</TITLE>\n    </HEAD>\n\n    <BODY BGCOLOR="FFFFFF">\n    <HR>\n    <a href="http://google.com">Goog</a>\n    <H1>This is one header</H1>\n    <H2>This is a another Header</H2>\n    <P>Travel from\n        <P>\n        <B>SFO to JFK</B>\n        <BR>\n        <B><I>on May 2, 2015 at 2:00 pm. For details go to confirm.com </I></B>\n        <HR>\n        <div style="color:#0000FF">\n            <h3>Traveler <b> name </b> is\n            <p> John Doe </p>\n        </div>'

    _lowercase :							List[Any]   	=	'\n    <!DOCTYPE html>\n    <html>\n    <body>\n\n    <h1>My First Heading</h1>\n    <p>My first paragraph.</p>\n\n    </body>\n    </html>\n    '

    return [html_string_a, html_string_a]






@require_bsa
class _lowerCamelCase(		_a,				unittest.TestCase     ):
       lowercase_				:			Tuple									=    MarkupLMFeatureExtractor if is_bsa_available() else None
       def     UpperCamelCase  (      self) ->     Optional[int]:




           """simple docstring"""

           _lowercase :							Tuple   	=	MarkupLMFeatureExtractionTester(self)
       @property
       def     UpperCamelCase  (      self) ->     List[Any]:




           """simple docstring"""

           return self.feature_extract_tester.prepare_feat_extract_dict()




       def     UpperCamelCase  (      self) ->     List[str]:




           """simple docstring"""

           _lowercase :							int   	=	self.feature_extraction_class()

           # Test not batched input
           _lowercase :							List[Any]   	=	get_html_strings()[0]
           _lowercase :							Optional[Any]   	=	feature_extractor(lowerCamelCase)

           # fmt: off
           _lowercase :							str   	=	[['sample document', 'Goog', 'This is one header', 'This is a another Header', 'Travel from', 'SFO to JFK', 'on May 2, 2015 at 2:00 pm. For details go to confirm.com', 'Traveler', 'name', 'is', 'John Doe']]
           _lowercase :							Dict   	=	[['/html/head/title', '/html/body/a', '/html/body/h1', '/html/body/h2', '/html/body/p', '/html/body/p/p/b[1]', '/html/body/p/p/b[2]/i', '/html/body/p/p/div/h3', '/html/body/p/p/div/h3/b', '/html/body/p/p/div/h3', '/html/body/p/p/div/h3/p']]
           # fmt: on

           self.assertEqual(encoding.nodes,   lowerCamelCase)
           self.assertEqual(encoding.xpaths,   lowerCamelCase)

           # Test batched
           _lowercase :							Optional[int]   	=	get_html_strings()
           _lowercase :							Tuple   	=	feature_extractor(lowerCamelCase)

           # fmt: off
           _lowercase :							List[Any]   	=	expected_nodes + [['My First Heading', 'My first paragraph.']]
           _lowercase :							List[str]   	=	expected_xpaths + [['/html/body/h1', '/html/body/p']]

           self.assertEqual(len(encoding.nodes),   2)
           self.assertEqual(len(encoding.xpaths),   2)

           self.assertEqual(encoding.nodes,   lowerCamelCase)
           self.assertEqual(encoding.xpaths,   lowerCamelCase)


