



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


__SCREAMING_SNAKE_CASE           =  logging.get_logger(__name__)

__SCREAMING_SNAKE_CASE           =  {
    """salesforce/blip2-opt-2.7b""": """https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json""",
}

class 	lowerCamelCase_    ( _A						):






						'''simple docstring'''
						a__   =  "blip_2_vision_model"







						def __init__(	self      :			Tuple	,	__lowerCamelCase      :			Any=14_08	,	__lowerCamelCase      :			Union[str, Any]=61_44	,	__lowerCamelCase      :			Any=39	,	__lowerCamelCase      :			Union[str, Any]=16	,	__lowerCamelCase      :			Any=2_24	,	__lowerCamelCase      :			Tuple=14	,	__lowerCamelCase      :			Dict="gelu"	,	__lowerCamelCase      :			str=0.00001	,	__lowerCamelCase      :			Dict=0.0	,	__lowerCamelCase      :			Any=1e-10	,	__lowerCamelCase      :			List[Any]=True	,	**__lowerCamelCase      :			Union[str, Any]	,	)      ->				List[Any]:
									super().__init__(**__lowerCamelCase )

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







						@classmethod
						def 			SCREAMING_SNAKE_CASE__		(	cls      :			str	,	__lowerCamelCase      :			Union[str, os.PathLike]	,	**__lowerCamelCase      :			Optional[Any] )      ->				"PretrainedConfig":
									cls._set_token_in_kwargs(__lowerCamelCase )

									A							:					int              =						cls.get_config_dict(__lowerCamelCase	,	**__lowerCamelCase )

									# get the vision config dict if we are loading from Blip2Config
									if config_dict.get("model_type" ) == "blip-2":
												A							:					Tuple              =						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						):






						'''simple docstring'''
						a__   =  "blip_2_qformer"







						def __init__(	self      :			Tuple	,	__lowerCamelCase      :			Union[str, Any]=3_05_22	,	__lowerCamelCase      :			Union[str, Any]=7_68	,	__lowerCamelCase      :			Tuple=12	,	__lowerCamelCase      :			Dict=12	,	__lowerCamelCase      :			Optional[int]=30_72	,	__lowerCamelCase      :			int="gelu"	,	__lowerCamelCase      :			Any=0.1	,	__lowerCamelCase      :			int=0.1	,	__lowerCamelCase      :			str=5_12	,	__lowerCamelCase      :			Any=0.02	,	__lowerCamelCase      :			Any=1e-12	,	__lowerCamelCase      :			Optional[Any]=0	,	__lowerCamelCase      :			List[Any]="absolute"	,	__lowerCamelCase      :			Any=2	,	__lowerCamelCase      :			str=14_08	,	**__lowerCamelCase      :			int	,	)      ->				Optional[Any]:
									super().__init__(pad_token_id=__lowerCamelCase	,	**__lowerCamelCase )

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







						@classmethod
						def 			SCREAMING_SNAKE_CASE__		(	cls      :			Union[str, Any]	,	__lowerCamelCase      :			Union[str, os.PathLike]	,	**__lowerCamelCase      :			Optional[int] )      ->				"PretrainedConfig":
									cls._set_token_in_kwargs(__lowerCamelCase )

									A							:					Union[str, Any]              =						cls.get_config_dict(__lowerCamelCase	,	**__lowerCamelCase )

									# get the qformer config dict if we are loading from Blip2Config
									if config_dict.get("model_type" ) == "blip-2":
												A							:					Optional[int]              =						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(__lowerCamelCase	,	**__lowerCamelCase )







class 	lowerCamelCase_    ( _A						):






						'''simple docstring'''
						a__   =  "blip-2"
						a__   =  True







						def __init__(	self      :			Union[str, Any]	,	__lowerCamelCase      :			Any=None	,	__lowerCamelCase      :			Optional[int]=None	,	__lowerCamelCase      :			Union[str, Any]=None	,	__lowerCamelCase      :			Tuple=32	,	**__lowerCamelCase      :			Any )      ->				Optional[int]:
									super().__init__(**__lowerCamelCase )

									if vision_config is None:
												A							:					List[str]              =						{}
												logger.info("vision_config is None. initializing the Blip2VisionConfig with default values." )

									if qformer_config is None:
												A							:					Dict              =						{}
												logger.info("qformer_config is None. Initializing the Blip2QFormerConfig with default values." )

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

									A							:					List[Any]              =						BlipaVisionConfig(**__lowerCamelCase )
									A							:					List[Any]              =						BlipaQFormerConfig(**__lowerCamelCase )
									A							:					Union[str, Any]              =						text_config["model_type"] if "model_type" in text_config else "opt"
									A							:					Tuple              =						CONFIG_MAPPING[text_model_type](**__lowerCamelCase )

									A							:					Tuple              =						self.text_config.tie_word_embeddings
									A							:					Union[str, Any]              =						self.text_config.is_encoder_decoder

									A							:					Union[str, Any]              =						num_query_tokens
									A							:					str              =						self.vision_config.hidden_size
									A							:					int              =						self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
									A							:					Any              =						1.0
									A							:					Optional[int]              =						0.02







						@classmethod
						def 			SCREAMING_SNAKE_CASE__		(	cls      :			Optional[int]	,	__lowerCamelCase      :			BlipaVisionConfig	,	__lowerCamelCase      :			BlipaQFormerConfig	,	__lowerCamelCase      :			PretrainedConfig	,	**__lowerCamelCase      :			Tuple	,	)      ->				Tuple:
									return cls(
									    vision_config=vision_config.to_dict()	,	qformer_config=qformer_config.to_dict()	,	text_config=text_config.to_dict()	,	**__lowerCamelCase	,	)







						def 			SCREAMING_SNAKE_CASE__		(	self      :			Tuple )      ->				int:
									A							:					str              =						copy.deepcopy(self.__dict__ )
									A							:					List[str]              =						self.vision_config.to_dict()
									A							:					int              =						self.qformer_config.to_dict()
									A							:					Dict              =						self.text_config.to_dict()
									A							:					Optional[int]              =						self.__class__.model_type
									return output




from sklearn.metrics import recall_score

import datasets


__SCREAMING_SNAKE_CASE           =  """
Recall is the fraction of the positive examples that were correctly labeled by the model as positive. It can be computed with the equation:
Recall = TP / (TP + FN)
Where TP is the true positives and FN is the false negatives.
"""


__SCREAMING_SNAKE_CASE           =  """
Args:
- **predictions** (`list` of `int`): The predicted labels.
- **references** (`list` of `int`): The ground truth labels.
- **labels** (`list` of `int`): The set of labels to include when `average` is not set to `binary`, and their order when average is `None`. Labels present in the data can be excluded in this input, for example to calculate a multiclass average ignoring a majority negative class, while labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in y_true and y_pred are used in sorted order. Defaults to None.
- **pos_label** (`int`): The class label to use as the 'positive class' when calculating the recall. Defaults to `1`.
- **average** (`string`): This parameter is required for multiclass/multilabel targets. If None, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`.
    - `'binary'`: Only report results for the class specified by `pos_label`. This is applicable only if the target labels and predictions are binary.
    - `'micro'`: Calculate metrics globally by counting the total true positives, false negatives, and false positives.
    - `'macro'`: Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.
    - `'weighted'`: Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. Note that it can result in an F-score that is not between precision and recall.
    - `'samples'`: Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).
- **sample_weight** (`list` of `float`): Sample weights Defaults to `None`.
- **zero_division** (): Sets the value to return when there is a zero division. Defaults to .
    - `'warn'`: If there is a zero division, the return value is `0`, but warnings are also raised.
    - `0`: If there is a zero division, the return value is `0`.
    - `1`: If there is a zero division, the return value is `1`.

Returns:
- **recall** (`float`, or `array` of `float`): Either the general recall score, or the recall scores for individual classes, depending on the values input to `labels` and `average`. Minimum possible value is 0. Maximum possible value is 1. A higher recall means that more of the positive examples have been labeled correctly. Therefore, a higher recall is generally considered better.

Examples:

    Example 1-A simple example with some errors
        >>> recall_metric = datasets.load_metric('recall')
        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1])
        >>> print(results)
        {'recall': 0.6666666666666666}

    Example 2-The same example as Example 1, but with `pos_label=0` instead of the default `pos_label=1`.
        >>> recall_metric = datasets.load_metric('recall')
        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], pos_label=0)
        >>> print(results)
        {'recall': 0.5}

    Example 3-The same example as Example 1, but with `sample_weight` included.
        >>> recall_metric = datasets.load_metric('recall')
        >>> sample_weight = [0.9, 0.2, 0.9, 0.3, 0.8]
        >>> results = recall_metric.compute(references=[0, 0, 1, 1, 1], predictions=[0, 1, 0, 1, 1], sample_weight=sample_weight)
        >>> print(results)
        {'recall': 0.55}

    Example 4-A multiclass example, using different averages.
        >>> recall_metric = datasets.load_metric('recall')
        >>> predictions = [0, 2, 1, 0, 0, 1]
        >>> references = [0, 1, 2, 0, 1, 2]
        >>> results = recall_metric.compute(predictions=predictions, references=references, average='macro')
        >>> print(results)
        {'recall': 0.3333333333333333}
        >>> results = recall_metric.compute(predictions=predictions, references=references, average='micro')
        >>> print(results)
        {'recall': 0.3333333333333333}
        >>> results = recall_metric.compute(predictions=predictions, references=references, average='weighted')
        >>> print(results)
        {'recall': 0.3333333333333333}
        >>> results = recall_metric.compute(predictions=predictions, references=references, average=None)
        >>> print(results)
        {'recall': array([1., 0., 0.])}
"""


__SCREAMING_SNAKE_CASE           =  """
@article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011}
"""

@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION						,_KWARGS_DESCRIPTION						)
class 	lowerCamelCase_    ( datasets.Metric						):






						'''simple docstring'''







						def 			SCREAMING_SNAKE_CASE__		(	self      :			Optional[Any] )      ->				str:
									return datasets.MetricInfo(
									    description=_DESCRIPTION	,	citation=_CITATION	,	inputs_description=_KWARGS_DESCRIPTION	,	features=datasets.Features(
									        {
									            "predictions": datasets.Sequence(datasets.Value("int32" ) ),
									            "references": datasets.Sequence(datasets.Value("int32" ) ),
									        }
									        if self.config_name == "multilabel"
									        else {
									            "predictions": datasets.Value("int32" ),
									            "references": datasets.Value("int32" ),
									        } )	,	reference_urls=["https://scikit-learn.org/stable/modules/generated/sklearn.metrics.recall_score.html"]	,	)







						def 			SCREAMING_SNAKE_CASE__		(	self      :			Any	,	__lowerCamelCase      :			int	,	__lowerCamelCase      :			Dict	,	__lowerCamelCase      :			str=None	,	__lowerCamelCase      :			List[Any]=1	,	__lowerCamelCase      :			Tuple="binary"	,	__lowerCamelCase      :			Tuple=None	,	__lowerCamelCase      :			Tuple="warn"	,	)      ->				Optional[Any]:
									A							:					str              =						recall_score(
									    __lowerCamelCase	,	__lowerCamelCase	,	labels=__lowerCamelCase	,	pos_label=__lowerCamelCase	,	average=__lowerCamelCase	,	sample_weight=__lowerCamelCase	,	zero_division=__lowerCamelCase	,	)
									return {"recall": float(__lowerCamelCase ) if score.size == 1 else score}