"""simple docstring"""





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


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

_UpperCamelCase     :		int											=					"\\nROUGE, or Recall-Oriented Understudy for Gisting Evaluation, is a set of metrics and a software package used for\nevaluating automatic summarization and machine translation software in natural language processing.\nThe metrics compare an automatically produced summary or translation against a reference or a set of references (human-produced) summary or translation.\n\nNote that ROUGE is case insensitive, meaning that upper case letters are treated the same way as lower case letters.\n\nThis metrics is a wrapper around Google Research reimplementation of ROUGE:\nhttps://github.com/google-research/google-research/tree/master/rouge\n"

_UpperCamelCase     :		Union[str, Any]											=					"\nCalculates average rouge scores for a list of hypotheses and references\nArgs:\n    predictions: list of predictions to score. Each prediction\n        should be a string with tokens separated by spaces.\n    references: list of reference for each prediction. Each\n        reference should be a string with tokens separated by spaces.\n    rouge_types: A list of rouge types to calculate.\n        Valid names:\n        `\"rouge{n}\"` (e.g. `\"rouge1\"`, `\"rouge2\"`) where: {n} is the n-gram based scoring,\n        `\"rougeL\"`: Longest common subsequence based scoring.\n        `\"rougeLSum\"`: rougeLsum splits text using `\"\n\"`.\n        See details in https://github.com/huggingface/datasets/issues/617\n    use_stemmer: Bool indicating whether Porter stemmer should be used to strip word suffixes.\n    use_aggregator: Return aggregates if this is set to True\nReturns:\n    rouge1: rouge_1 (precision, recall, f1),\n    rouge2: rouge_2 (precision, recall, f1),\n    rougeL: rouge_l (precision, recall, f1),\n    rougeLsum: rouge_lsum (precision, recall, f1)\nExamples:\n\n    >>> rouge = datasets.load_metric('rouge')\n    >>> predictions = [\"hello there\", \"general kenobi\"]\n    >>> references = [\"hello there\", \"general kenobi\"]\n    >>> results = rouge.compute(predictions=predictions, references=references)\n    >>> print(list(results.keys()))\n    ['rouge1', 'rouge2', 'rougeL', 'rougeLsum']\n    >>> print(results[\"rouge1\"])\n    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))\n    >>> print(results[\"rouge1\"].mid.fmeasure)\n    1.0\n"


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


      def 	_UpperCAmelCase (     self							) ->      int:
             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 	_UpperCAmelCase (     self	,    a	,    a	,    a=None	,    a=True	,    a=False							) ->      str:
             if rouge_types is None:
                    lowercase__    :	Union[str, Any]     					=			['rouge1', 'rouge2', 'rougeL', 'rougeLsum']

             lowercase__    :	Tuple     					=			rouge_scorer.RougeScorer(rouge_types=a	,    use_stemmer=a							)
             if use_aggregator:
                    lowercase__    :	Dict     					=			scoring.BootstrapAggregator()
             else:
                    lowercase__    :	List[str]     					=			[]

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

             if use_aggregator:
                    lowercase__    :	List[Any]     					=			aggregator.aggregate()
             else:
                    lowercase__    :	Tuple     					=			{}
                    for key in scores[0]:
                           lowercase__    :	List[str]     					=			[score[key] for score in scores]

             return result


"""simple docstring"""





# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import copy
import importlib.metadata
import json
import os
from dataclasses import dataclass
from typing import Any, Dict, Union

from packaging import version

from ..utils import is_torch_available, logging


if is_torch_available():
       import torch


_UpperCamelCase     :		int											=					logging.get_logger(__name__)


@dataclass
class   UpperCAmelCase_			:


      def __init__(     self	,    a=False	,    a=False	,    a=6.0	,    a=None	,    a=False	,    a=False	,    a=None	,    a="fp4"	,    a=False	,    **a	,    ) ->      Tuple:
             lowercase__    :	str     					=			load_in_abit
             lowercase__    :	str     					=			load_in_abit
             lowercase__    :	List[str]     					=			llm_inta_threshold
             lowercase__    :	Dict     					=			llm_inta_skip_modules
             lowercase__    :	Tuple     					=			llm_inta_enable_fpaa_cpu_offload
             lowercase__    :	Any     					=			llm_inta_has_fpaa_weight
             lowercase__    :	Any     					=			bnb_abit_quant_type
             lowercase__    :	Dict     					=			bnb_abit_use_double_quant

             if bnb_abit_compute_dtype is None:
                    lowercase__    :	Dict     					=			torch.floataa
             elif isinstance(a	,    a							):
                    lowercase__    :	Any     					=			getattr(a	,    a							)
             elif isinstance(a	,    torch.dtype							):
                    lowercase__    :	Any     					=			bnb_abit_compute_dtype
             else:
                    raise ValueError('bnb_4bit_compute_dtype must be a string or a torch.dtype'							)

             self.post_init()


      def 	_UpperCAmelCase (     self							) ->      str:
             if not isinstance(self.llm_inta_threshold	,    a							):
                    raise ValueError('llm_int8_threshold must be a float'							)

             if self.llm_inta_skip_modules is not None and not isinstance(self.llm_inta_skip_modules	,    a							):
                    raise ValueError('llm_int8_skip_modules must be a list of strings'							)
             if not isinstance(self.llm_inta_enable_fpaa_cpu_offload	,    a							):
                    raise ValueError('llm_int8_enable_fp32_cpu_offload must be a boolean'							)

             if not isinstance(self.llm_inta_has_fpaa_weight	,    a							):
                    raise ValueError('llm_int8_has_fp16_weight must be a boolean'							)

             if self.bnb_abit_compute_dtype is not None and not isinstance(self.bnb_abit_compute_dtype	,    torch.dtype							):
                    raise ValueError('bnb_4bit_compute_dtype must be torch.dtype'							)

             if not isinstance(self.bnb_abit_quant_type	,    a							):
                    raise ValueError('bnb_4bit_quant_type must be a string'							)

             if not isinstance(self.bnb_abit_use_double_quant	,    a							):
                    raise ValueError('bnb_4bit_use_double_quant must be a boolean'							)

             if self.load_in_abit and not version.parse(importlib.metadata.version('bitsandbytes'							)							) >= version.parse(
                 '0.39.0'							):
                    raise ValueError(
                        '4 bit quantization requires bitsandbytes>=0.39.0 - please upgrade your bitsandbytes version'							)


      def 	_UpperCAmelCase (     self							) ->      Tuple:
             return self.load_in_abit or self.load_in_abit


      def 	_UpperCAmelCase (     self							) ->      List[str]:
             if self.load_in_abit:
                    return "llm_int8"
             elif self.load_in_abit and self.bnb_abit_quant_type == "fp4":
                    return "fp4"
             elif self.load_in_abit and self.bnb_abit_quant_type == "nf4":
                    return "nf4"
             else:
                    return None


      @classmethod
      def 	_UpperCAmelCase (     cls	,    a	,    a	,    **a							) ->      Optional[Any]:
             lowercase__    :	List[Any]     					=			cls(**a							)

             lowercase__    :	Union[str, Any]     					=			[]
             for key, value in kwargs.items():
                    if hasattr(a	,    a							):
                           setattr(a	,    a	,    a							)
                           to_remove.append(a							)
             for key in to_remove:
                    kwargs.pop(a	,    a							)

             if return_unused_kwargs:
                    return config, kwargs
             else:
                    return config


      def 	_UpperCAmelCase (     self	,    a							) ->      Dict:
             with open(a	,    'w'	,    encoding='utf-8'							) as writer:
                    lowercase__    :	Any     					=			self.to_dict()
                    lowercase__    :	str     					=			json.dumps(a	,    indent=2	,    sort_keys=a							) + '\n'

                    writer.write(a							)


      def 	_UpperCAmelCase (     self							) ->      Dict[str, Any]:
             lowercase__    :	Optional[Any]     					=			copy.deepcopy(self.__dict__							)
             lowercase__    :	Any     					=			str(output['bnb_4bit_compute_dtype']							).split('.'							)[1]

             return output


      def __repr__(     self							) ->      Dict:
             return f"""{self.__class__.__name__} {self.to_json_string()}"""


      def 	_UpperCAmelCase (     self	,    a = True							) ->      str:
             if use_diff is True:
                    lowercase__    :	List[Any]     					=			self.to_diff_dict()
             else:
                    lowercase__    :	List[str]     					=			self.to_dict()
             return json.dumps(a	,    indent=2	,    sort_keys=a							) + "\n"


      def 	_UpperCAmelCase (     self							) ->      Dict[str, Any]:
             lowercase__    :	Tuple     					=			self.to_dict()

             # get the default config dict
             lowercase__    :	Optional[Any]     					=			BitsAndBytesConfig().to_dict()

             lowercase__    :	int     					=			{}

             # only serialize values that differ from the default config
             for key, value in config_dict.items():
                    if value != default_config_dict[key]:
                           lowercase__    :	Optional[int]     					=			value

             return serializable_config_dict

