





import absl  # noqa: F401 # Here to have a nice missing dependency error message early on
import nltk  # noqa: F401 # Here to have a nice missing dependency error message early on
import numpy  # noqa: F401 # Here to have a nice missing dependency error message early on
import six  # noqa: F401 # Here to have a nice missing dependency error message early on
from rouge_score import rouge_scorer, scoring

import datasets


SCREAMING_SNAKE_CASE_						   =       """\
@inproceedings{lin-2004-rouge,
    title = \"{ROUGE}: A Package for Automatic Evaluation of Summaries\",
    author = \"Lin, Chin-Yew\",
    booktitle = \"Text Summarization Branches Out\",
    month = jul,
    year = \"2004\",
    address = \"Barcelona, Spain\",
    publisher = \"Association for Computational Linguistics\",
    url = \"https://www.aclweb.org/anthology/W04-1013\",
    pages = \"74--81\",
}
"""

SCREAMING_SNAKE_CASE_						   =       """\
ROUGE, or Recall-Oriented Understudy for Gisting Evaluation, is a set of metrics and a software package used for
evaluating automatic summarization and machine translation software in natural language processing.
The metrics compare an automatically produced summary or translation against a reference or a set of references (human-produced) summary or translation.

Note that ROUGE is case insensitive, meaning that upper case letters are treated the same way as lower case letters.

This metrics is a wrapper around Google Research reimplementation of ROUGE:
https://github.com/google-research/google-research/tree/master/rouge
"""

SCREAMING_SNAKE_CASE_						   =       """
Calculates average rouge scores for a list of hypotheses and references
Args:
    predictions: list of predictions to score. Each prediction
        should be a string with tokens separated by spaces.
    references: list of reference for each prediction. Each
        reference should be a string with tokens separated by spaces.
    rouge_types: A list of rouge types to calculate.
        Valid names:
        `\"rouge{n}\"` (e.g. `\"rouge1\"`, `\"rouge2\"`) where: {n} is the n-gram based scoring,
        `\"rougeL\"`: Longest common subsequence based scoring.
        `\"rougeLSum\"`: rougeLsum splits text using `\"\n\"`.
        See details in https://github.com/huggingface/datasets/issues/617
    use_stemmer: Bool indicating whether Porter stemmer should be used to strip word suffixes.
    use_aggregator: Return aggregates if this is set to True
Returns:
    rouge1: rouge_1 (precision, recall, f1),
    rouge2: rouge_2 (precision, recall, f1),
    rougeL: rouge_l (precision, recall, f1),
    rougeLsum: rouge_lsum (precision, recall, f1)
Examples:

    >>> rouge = datasets.load_metric('rouge')
    >>> predictions = [\"hello there\", \"general kenobi\"]
    >>> references = [\"hello there\", \"general kenobi\"]
    >>> results = rouge.compute(predictions=predictions, references=references)
    >>> print(list(results.keys()))
    ['rouge1', 'rouge2', 'rougeL', 'rougeLsum']
    >>> print(results[\"rouge1\"])
    AggregateScore(low=Score(precision=1.0, recall=1.0, fmeasure=1.0), mid=Score(precision=1.0, recall=1.0, fmeasure=1.0), high=Score(precision=1.0, recall=1.0, fmeasure=1.0))
    >>> print(results[\"rouge1\"].mid.fmeasure)
    1.0
"""

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



     '''simple docstring'''

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




           '''simple docstring'''


           return datasets.MetricInfo(
               description=_DESCRIPTION						,citation=_CITATION						,inputs_description=_KWARGS_DESCRIPTION						,features=datasets.Features(
                   {
                       """predictions""": datasets.Value("""string"""						,id="""sequence"""       ),
                       """references""": datasets.Value("""string"""						,id="""sequence"""       ),
                   }       )						,codebase_urls=["""https://github.com/google-research/google-research/tree/master/rouge"""]						,reference_urls=[
                   """https://en.wikipedia.org/wiki/ROUGE_(metric)""",
                   """https://github.com/google-research/google-research/tree/master/rouge""",
               ]						,)






     def 				SCREAMING_SNAKE_CASE__  (							self						:    List[Any]						,lowerCamelCase__						:    Optional[Any]						,lowerCamelCase__						:    Dict						,lowerCamelCase__						:    Tuple=None						,lowerCamelCase__						:    Optional[Any]=True						,lowerCamelCase__						:    Optional[Any]=False       )     ->		Dict:




           '''simple docstring'''


           if rouge_types is None:
                 SCREAMING_SNAKE_CASE		=						["""rouge1""", """rouge2""", """rougeL""", """rougeLsum"""]

           SCREAMING_SNAKE_CASE		=						rouge_scorer.RougeScorer(rouge_types=lowerCamelCase__						,use_stemmer=lowerCamelCase__       )
           if use_aggregator:
                 SCREAMING_SNAKE_CASE		=						scoring.BootstrapAggregator()
           else:
                 SCREAMING_SNAKE_CASE		=						[]

           for ref, pred in zip(lowerCamelCase__						,lowerCamelCase__       ):
                 SCREAMING_SNAKE_CASE		=						scorer.score(lowerCamelCase__						,lowerCamelCase__       )
                 if use_aggregator:
                       aggregator.add_scores(lowerCamelCase__       )
                 else:
                       scores.append(lowerCamelCase__       )

           if use_aggregator:
                 SCREAMING_SNAKE_CASE		=						aggregator.aggregate()
           else:
                 SCREAMING_SNAKE_CASE		=						{}
                 for key in scores[0]:
                       SCREAMING_SNAKE_CASE		=						[score[key] for score in scores]

           return result









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_						   =       {
    """microsoft/git-base""": """https://huggingface.co/microsoft/git-base/resolve/main/config.json""",
}

class 		UpperCamelCase__ (      lowerCAmelCase_   ):



     '''simple docstring'''

     __snake_case    :	Dict			=			"git_vision_model"






     def __init__(							self						:    List[Any]						,lowerCamelCase__						:    Dict=768						,lowerCamelCase__						:    Union[str, Any]=3072						,lowerCamelCase__						:    Optional[int]=12						,lowerCamelCase__						:    Tuple=12						,lowerCamelCase__						:    Tuple=3						,lowerCamelCase__						:    Optional[Any]=224						,lowerCamelCase__						:    Union[str, Any]=16						,lowerCamelCase__						:    List[Any]="quick_gelu"						,lowerCamelCase__						:    Optional[Any]=1e-5						,lowerCamelCase__						:    str=0.0						,lowerCamelCase__						:    Optional[int]=0.02						,**lowerCamelCase__						:    Union[str, Any]						,)     ->		Optional[int]:




           '''simple docstring'''


           super().__init__(**lowerCamelCase__       )

           SCREAMING_SNAKE_CASE		=						hidden_size
           SCREAMING_SNAKE_CASE		=						intermediate_size
           SCREAMING_SNAKE_CASE		=						num_hidden_layers
           SCREAMING_SNAKE_CASE		=						num_attention_heads
           SCREAMING_SNAKE_CASE		=						num_channels
           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						:    Tuple						,lowerCamelCase__						:    Union[str, os.PathLike]						,**lowerCamelCase__						:    int       )     ->		"PretrainedConfig":




           '''simple docstring'''


           cls._set_token_in_kwargs(lowerCamelCase__       )

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

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

class 		UpperCamelCase__ (      lowerCAmelCase_   ):



     '''simple docstring'''

     __snake_case    :	Dict			=			"git"






     def __init__(							self						:    Optional[int]						,lowerCamelCase__						:    int=None						,lowerCamelCase__						:    str=30522						,lowerCamelCase__						:    Tuple=768						,lowerCamelCase__						:    Union[str, Any]=6						,lowerCamelCase__						:    str=12						,lowerCamelCase__						:    List[str]=3072						,lowerCamelCase__						:    Dict="gelu"						,lowerCamelCase__						:    Tuple=0.1						,lowerCamelCase__						:    Any=0.1						,lowerCamelCase__						:    List[str]=1024						,lowerCamelCase__						:    List[str]=0.02						,lowerCamelCase__						:    str=1e-1_2						,lowerCamelCase__						:    Optional[int]=0						,lowerCamelCase__						:    Optional[int]="absolute"						,lowerCamelCase__						:    Optional[Any]=True						,lowerCamelCase__						:    str=False						,lowerCamelCase__						:    int=101						,lowerCamelCase__						:    int=102						,lowerCamelCase__						:    Dict=None						,**lowerCamelCase__						:    List[Any]						,)     ->		Optional[Any]:




           '''simple docstring'''


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

           if vision_config is None:
                 SCREAMING_SNAKE_CASE		=						{}
                 logger.info("""vision_config is None. initializing the GitVisionConfig with default values."""       )

           SCREAMING_SNAKE_CASE		=						GitVisionConfig(**lowerCamelCase__       )
           SCREAMING_SNAKE_CASE		=						vocab_size
           SCREAMING_SNAKE_CASE		=						hidden_size
           SCREAMING_SNAKE_CASE		=						num_hidden_layers
           SCREAMING_SNAKE_CASE		=						num_attention_heads
           SCREAMING_SNAKE_CASE		=						hidden_act
           SCREAMING_SNAKE_CASE		=						intermediate_size
           SCREAMING_SNAKE_CASE		=						hidden_dropout_prob
           SCREAMING_SNAKE_CASE		=						attention_probs_dropout_prob
           SCREAMING_SNAKE_CASE		=						max_position_embeddings
           SCREAMING_SNAKE_CASE		=						initializer_range
           SCREAMING_SNAKE_CASE		=						layer_norm_eps
           SCREAMING_SNAKE_CASE		=						position_embedding_type
           SCREAMING_SNAKE_CASE		=						use_cache
           SCREAMING_SNAKE_CASE		=						tie_word_embeddings
           SCREAMING_SNAKE_CASE		=						num_image_with_embedding

           SCREAMING_SNAKE_CASE		=						bos_token_id
           SCREAMING_SNAKE_CASE		=						eos_token_id






     def 				SCREAMING_SNAKE_CASE__  (							self						:    Dict       )     ->		Optional[int]:




           '''simple docstring'''


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


