





import copy
import os
from typing import Union

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


SCREAMING_SNAKE_CASE_		     =		logging.get_logger(__name__)

SCREAMING_SNAKE_CASE_		     =		{
    'Salesforce/blip-vqa-base': 'https://huggingface.co/Salesforce/blip-vqa-base/resolve/main/config.json',
    'Salesforce/blip-vqa-capfit-large': (
        'https://huggingface.co/Salesforce/blip-vqa-base-capfit/resolve/main/config.json'
    ),
    'Salesforce/blip-image-captioning-base': (
        'https://huggingface.co/Salesforce/blip-image-captioning-base/resolve/main/config.json'
    ),
    'Salesforce/blip-image-captioning-large': (
        'https://huggingface.co/Salesforce/blip-image-captioning-large/resolve/main/config.json'
    ),
    'Salesforce/blip-itm-base-coco': 'https://huggingface.co/Salesforce/blip-itm-base-coco/resolve/main/config.json',
    'Salesforce/blip-itm-large-coco': 'https://huggingface.co/Salesforce/blip-itm-large-coco/resolve/main/config.json',
    'Salesforce/blip-itm-base-flikr': 'https://huggingface.co/Salesforce/blip-itm-base-flikr/resolve/main/config.json',
    'Salesforce/blip-itm-large-flikr': (
        'https://huggingface.co/Salesforce/blip-itm-large-flikr/resolve/main/config.json'
    ),
}

class 	UpperCamelCase__				(   _A     ):



     '''simple docstring'''

     __snake_case					:			Union[str, Any]				=    "blip_text_model"






     def __init__(							self		:					List[str]		,lowerCamelCase__		:					int=30524		,lowerCamelCase__		:					Dict=768		,lowerCamelCase__		:					Tuple=768		,lowerCamelCase__		:					str=3072		,lowerCamelCase__		:					Optional[int]=768		,lowerCamelCase__		:					Dict=12		,lowerCamelCase__		:					str=8		,lowerCamelCase__		:					int=512		,lowerCamelCase__		:					List[Any]="gelu"		,lowerCamelCase__		:					List[str]=1e-1_2		,lowerCamelCase__		:					Optional[Any]=0.0		,lowerCamelCase__		:					Optional[Any]=0.0		,lowerCamelCase__		:					Tuple=0.02		,lowerCamelCase__		:					Dict=30522		,lowerCamelCase__		:					str=2		,lowerCamelCase__		:					str=0		,lowerCamelCase__		:					Union[str, Any]=102		,lowerCamelCase__		:					Any=True		,lowerCamelCase__		:					Optional[Any]=True		,**lowerCamelCase__		:					List[str]		,)  ->	Tuple:




           '''simple docstring'''


           super().__init__(
               pad_token_id=UpperCamelCase__		,bos_token_id=UpperCamelCase__		,eos_token_id=UpperCamelCase__		,sep_token_id=UpperCamelCase__		,**UpperCamelCase__		,)

           SCREAMING_SNAKE_CASE	=		vocab_size
           SCREAMING_SNAKE_CASE	=		hidden_size
           SCREAMING_SNAKE_CASE	=		encoder_hidden_size
           SCREAMING_SNAKE_CASE	=		intermediate_size
           SCREAMING_SNAKE_CASE	=		projection_dim
           SCREAMING_SNAKE_CASE	=		hidden_dropout_prob
           SCREAMING_SNAKE_CASE	=		num_hidden_layers
           SCREAMING_SNAKE_CASE	=		num_attention_heads
           SCREAMING_SNAKE_CASE	=		max_position_embeddings
           SCREAMING_SNAKE_CASE	=		layer_norm_eps
           SCREAMING_SNAKE_CASE	=		hidden_act
           SCREAMING_SNAKE_CASE	=		initializer_range
           SCREAMING_SNAKE_CASE	=		attention_probs_dropout_prob
           SCREAMING_SNAKE_CASE	=		is_decoder
           SCREAMING_SNAKE_CASE	=		use_cache






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




           '''simple docstring'''


           cls._set_token_in_kwargs(UpperCamelCase__ )

           SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		cls.get_config_dict(UpperCamelCase__		,**UpperCamelCase__ )

           # get the text config dict if we are loading from BlipConfig
           if config_dict.get("""model_type""" ) == "blip":
                 SCREAMING_SNAKE_CASE	=		config_dict["""text_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(UpperCamelCase__		,**UpperCamelCase__ )

class 	UpperCamelCase__				(   _A     ):



     '''simple docstring'''

     __snake_case					:			Optional[int]				=    "blip_vision_model"






     def __init__(							self		:					Dict		,lowerCamelCase__		:					Optional[Any]=768		,lowerCamelCase__		:					Tuple=3072		,lowerCamelCase__		:					Optional[int]=512		,lowerCamelCase__		:					Optional[Any]=12		,lowerCamelCase__		:					List[str]=12		,lowerCamelCase__		:					Union[str, Any]=384		,lowerCamelCase__		:					int=16		,lowerCamelCase__		:					int="gelu"		,lowerCamelCase__		:					List[str]=1e-5		,lowerCamelCase__		:					Union[str, Any]=0.0		,lowerCamelCase__		:					Optional[int]=1e-1_0		,**lowerCamelCase__		:					int		,)  ->	List[str]:




           '''simple docstring'''


           super().__init__(**UpperCamelCase__ )

           SCREAMING_SNAKE_CASE	=		hidden_size
           SCREAMING_SNAKE_CASE	=		intermediate_size
           SCREAMING_SNAKE_CASE	=		projection_dim
           SCREAMING_SNAKE_CASE	=		num_hidden_layers
           SCREAMING_SNAKE_CASE	=		num_attention_heads
           SCREAMING_SNAKE_CASE	=		patch_size
           SCREAMING_SNAKE_CASE	=		image_size
           SCREAMING_SNAKE_CASE	=		initializer_range
           SCREAMING_SNAKE_CASE	=		attention_dropout
           SCREAMING_SNAKE_CASE	=		layer_norm_eps
           SCREAMING_SNAKE_CASE	=		hidden_act






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




           '''simple docstring'''


           cls._set_token_in_kwargs(UpperCamelCase__ )

           SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		cls.get_config_dict(UpperCamelCase__		,**UpperCamelCase__ )

           # get the vision config dict if we are loading from BlipConfig
           if config_dict.get("""model_type""" ) == "blip":
                 SCREAMING_SNAKE_CASE	=		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(UpperCamelCase__		,**UpperCamelCase__ )

class 	UpperCamelCase__				(   _A     ):



     '''simple docstring'''

     __snake_case					:			int				=    "blip"
     __snake_case					:			Tuple				=    True






     def __init__(							self		:					int		,lowerCamelCase__		:					int=None		,lowerCamelCase__		:					Any=None		,lowerCamelCase__		:					int=512		,lowerCamelCase__		:					int=2.6592		,lowerCamelCase__		:					Optional[int]=256		,**lowerCamelCase__		:					Dict		,)  ->	str:




           '''simple docstring'''


           super().__init__(**UpperCamelCase__ )

           if text_config is None:
                 SCREAMING_SNAKE_CASE	=		{}
                 logger.info("""`text_config` is `None`. Initializing the `BlipTextConfig` with default values.""" )

           if vision_config is None:
                 SCREAMING_SNAKE_CASE	=		{}
                 logger.info("""`vision_config` is `None`. Initializing the `BlipVisionConfig` with default values.""" )

           SCREAMING_SNAKE_CASE	=		BlipTextConfig(**UpperCamelCase__ )
           SCREAMING_SNAKE_CASE	=		BlipVisionConfig(**UpperCamelCase__ )

           SCREAMING_SNAKE_CASE	=		self.vision_config.hidden_size

           SCREAMING_SNAKE_CASE	=		projection_dim
           SCREAMING_SNAKE_CASE	=		logit_scale_init_value
           SCREAMING_SNAKE_CASE	=		1.0
           SCREAMING_SNAKE_CASE	=		0.02
           SCREAMING_SNAKE_CASE	=		image_text_hidden_size






     @classmethod
     def        SCREAMING_SNAKE_CASE__						(							cls		:					Any		,lowerCamelCase__		:					BlipTextConfig		,lowerCamelCase__		:					BlipVisionConfig		,**lowerCamelCase__		:					Optional[int] )  ->	List[Any]:




           '''simple docstring'''


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






     def        SCREAMING_SNAKE_CASE__						(							self		:					Dict )  ->	List[str]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		copy.deepcopy(self.__dict__ )
           SCREAMING_SNAKE_CASE	=		self.text_config.to_dict()
           SCREAMING_SNAKE_CASE	=		self.vision_config.to_dict()
           SCREAMING_SNAKE_CASE	=		self.__class__.model_type
           return output









from typing import Dict, List

from nltk.translate import gleu_score

import datasets
from datasets import MetricInfo


SCREAMING_SNAKE_CASE_		     = """\
@misc{wu2016googles,
      title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},
      author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey
              and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin
              Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto
              Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and
              Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes
              and Jeffrey Dean},
      year={2016},
      eprint={1609.08144},
      archivePrefix={arXiv},
      primaryClass={cs.CL}
}
"""

SCREAMING_SNAKE_CASE_		     = """\
The BLEU score has some undesirable properties when used for single
sentences, as it was designed to be a corpus measure. We therefore
use a slightly different score for our RL experiments which we call
the 'GLEU score'. For the GLEU score, we record all sub-sequences of
1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then
compute a recall, which is the ratio of the number of matching n-grams
to the number of total n-grams in the target (ground truth) sequence,
and a precision, which is the ratio of the number of matching n-grams
to the number of total n-grams in the generated output sequence. Then
GLEU score is simply the minimum of recall and precision. This GLEU
score's range is always between 0 (no matches) and 1 (all match) and
it is symmetrical when switching output and target. According to
our experiments, GLEU score correlates quite well with the BLEU
metric on a corpus level but does not have its drawbacks for our per
sentence reward objective.
"""

SCREAMING_SNAKE_CASE_		     = """\
Computes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.
Instead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching
tokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.

Args:
    predictions (list of str): list of translations to score.
        Each translation should be tokenized into a list of tokens.
    references (list of list of str): list of lists of references for each translation.
        Each reference should be tokenized into a list of tokens.
    min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.
    max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.

Returns:
    'google_bleu': google_bleu score

Examples:
    Example 1:
        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',
        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',
        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']
        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',
        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',
        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']

        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',
        ...         'interested', 'in', 'world', 'history']
        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',
        ...          'because', 'he', 'read', 'the', 'book']

        >>> list_of_references = [[ref1a], [ref2a]]
        >>> hypotheses = [hyp1, hyp2]
        >>> google_bleu = datasets.load_metric(\"google_bleu\")
        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)
        >>> print(round(results[\"google_bleu\"], 2))
        0.44

    Example 2:
        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',
        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',
        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']
        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',
        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',
        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']
        >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',
        ...          'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',
        ...          'heed', 'the', 'cat', 'commands']
        >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',
        ...          'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',
        ...          'of', 'the', 'cat']

        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',
        ...         'interested', 'in', 'world', 'history']
        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',
        ...          'because', 'he', 'read', 'the', 'book']

        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]
        >>> hypotheses = [hyp1, hyp2]
        >>> google_bleu = datasets.load_metric(\"google_bleu\")
        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)
        >>> print(round(results[\"google_bleu\"], 2))
        0.61

    Example 3:
        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',
        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',
        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']
        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',
        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',
        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']
        >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',
        ...          'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',
        ...          'heed', 'the', 'cat', 'commands']
        >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',
        ...          'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',
        ...          'of', 'the', 'cat']

        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',
        ...         'interested', 'in', 'world', 'history']
        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',
        ...          'because', 'he', 'read', 'the', 'book']

        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]
        >>> hypotheses = [hyp1, hyp2]
        >>> google_bleu = datasets.load_metric(\"google_bleu\")
        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)
        >>> print(round(results[\"google_bleu\"], 2))
        0.53

    Example 4:
        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',
        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',
        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']
        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',
        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',
        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']
        >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',
        ...          'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',
        ...          'heed', 'the', 'cat', 'commands']
        >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',
        ...          'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',
        ...          'of', 'the', 'cat']

        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',
        ...         'interested', 'in', 'world', 'history']
        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',
        ...          'because', 'he', 'read', 'the', 'book']

        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]
        >>> hypotheses = [hyp1, hyp2]
        >>> google_bleu = datasets.load_metric(\"google_bleu\")
        >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)
        >>> print(round(results[\"google_bleu\"], 2))
        0.4
"""

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



     '''simple docstring'''

     def        SCREAMING_SNAKE_CASE__						(							self		:					List[str] )  ->	MetricInfo:




           '''simple docstring'''


           return datasets.MetricInfo(
               description=_DESCRIPTION		,citation=_CITATION		,inputs_description=_KWARGS_DESCRIPTION		,features=datasets.Features(
                   {
                       """predictions""": datasets.Sequence(datasets.Value("""string"""		,id="""token""" )		,id="""sequence""" ),
                       """references""": datasets.Sequence(
                           datasets.Sequence(datasets.Value("""string"""		,id="""token""" )		,id="""sequence""" )		,id="""references""" ),
                   } )		,)






     def        SCREAMING_SNAKE_CASE__						(							self		:					List[str]		,lowerCamelCase__		:					List[List[List[str]]]		,lowerCamelCase__		:					List[List[str]]		,lowerCamelCase__		:					int = 1		,lowerCamelCase__		:					int = 4		,)  ->	Dict[str, float]:




           '''simple docstring'''


           return {
               "google_bleu": gleu_score.corpus_gleu(
                   list_of_references=lowerCamelCase__		,hypotheses=lowerCamelCase__		,min_len=lowerCamelCase__		,max_len=lowerCamelCase__ )
           }


