






from sklearn.metrics import precision_score

import datasets


__UpperCAmelCase      =				"\nPrecision is the fraction of correctly labeled positive examples out of all of the examples that were labeled as positive. It is computed via the equation:\nPrecision = TP / (TP + FP)\nwhere TP is the True positives (i.e. the examples correctly labeled as positive) and FP is the False positive examples (i.e. the examples incorrectly labeled as positive).\n"


__UpperCAmelCase      =				"\nArgs:\n    predictions (`list` of `int`): Predicted class labels.\n    references (`list` of `int`): Actual class labels.\n    labels (`list` of `int`): The set of labels to include when `average` is not set to `'binary'`. If `average` is `None`, it should be the label order. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. 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 `predictions` and `references` are used in sorted order. Defaults to None.\n    pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.\n    average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`.\n\n        - 'binary': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary.\n        - 'micro': Calculate metrics globally by counting the total true positives, false negatives and false positives.\n        - 'macro': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n        - '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. This option can result in an F-score that is not between precision and recall.\n        - 'samples': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n    sample_weight (`list` of `float`): Sample weights Defaults to None.\n    zero_division (`int` or `string`): Sets the value to return when there is a zero division. Defaults to 'warn'.\n\n        - 0: Returns 0 when there is a zero division.\n        - 1: Returns 1 when there is a zero division.\n        - 'warn': Raises warnings and then returns 0 when there is a zero division.\n\nReturns:\n    precision (`float` or `array` of `float`): Precision score or list of precision scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate that fewer negative examples were incorrectly labeled as positive, which means that, generally, higher scores are better.\n\nExamples:\n\n    Example 1-A simple binary example\n        >>> precision_metric = datasets.load_metric(\"precision\")\n        >>> results = precision_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])\n        >>> print(results)\n        {'precision': 0.5}\n\n    Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.\n        >>> precision_metric = datasets.load_metric(\"precision\")\n        >>> results = precision_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)\n        >>> print(round(results['precision'], 2))\n        0.67\n\n    Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.\n        >>> precision_metric = datasets.load_metric(\"precision\")\n        >>> results = precision_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3])\n        >>> print(results)\n        {'precision': 0.23529411764705882}\n\n    Example 4-A multiclass example, with different values for the `average` input.\n        >>> predictions = [0, 2, 1, 0, 0, 1]\n        >>> references = [0, 1, 2, 0, 1, 2]\n        >>> results = precision_metric.compute(predictions=predictions, references=references, average='macro')\n        >>> print(results)\n        {'precision': 0.2222222222222222}\n        >>> results = precision_metric.compute(predictions=predictions, references=references, average='micro')\n        >>> print(results)\n        {'precision': 0.3333333333333333}\n        >>> results = precision_metric.compute(predictions=predictions, references=references, average='weighted')\n        >>> print(results)\n        {'precision': 0.2222222222222222}\n        >>> results = precision_metric.compute(predictions=predictions, references=references, average=None)\n        >>> print([round(res, 2) for res in results['precision']])\n        [0.67, 0.0, 0.0]\n"


__UpperCAmelCase      =				"\n@article{scikit-learn,\n    title={Scikit-learn: Machine Learning in {P}ython},\n    author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n    and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n    and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n    Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n    journal={Journal of Machine Learning Research},\n    volume={12},\n    pages={2825--2830},\n    year={2011}\n}\n"
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION			,							_KWARGS_DESCRIPTION	)
class 	a_(		datasets.Metric	):



     """simple docstring"""



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

      """simple docstring"""
      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.precision_score.html']  ,  )





     def     __UpperCamelCase						(		self					:	int  ,  lowerCAmelCase__					:	str  ,  lowerCAmelCase__					:	Any  ,  lowerCAmelCase__					:	Tuple=None  ,  lowerCAmelCase__					:	List[Any]=1  ,  lowerCAmelCase__					:	Dict="binary"  ,  lowerCAmelCase__					:	int=None  ,  lowerCAmelCase__					:	Tuple="warn"  ,  )							->	int:

      """simple docstring"""
      SCREAMING_SNAKE_CASE				    =		precision_score(
          lowerCAmelCase__  ,  lowerCAmelCase__  ,  labels=lowerCAmelCase__  ,  pos_label=lowerCAmelCase__  ,  average=lowerCAmelCase__  ,  sample_weight=lowerCAmelCase__  ,  zero_division=lowerCAmelCase__  ,  )
      return {"precision": float(lowerCAmelCase__) if score.size == 1 else score}








'''simple docstring'''

import csv
import json
import os

import datasets


# TODO: Add BibTeX citation
# Find for instance the citation on arxiv or on the dataset repo/website
__lowercase:		Tuple    						=  "\\n@InProceedings{huggingface:dataset,\ntitle = {A great new dataset},\nauthor={huggingface, Inc.\n},\nyear={2020}\n}\n"

# TODO: Add description of the dataset here
# You can copy an official description
__lowercase:		Optional[int]    						=  "\\nThis new dataset is designed to solve this great NLP task and is crafted with a lot of care.\n"

# TODO: Add a link to an official homepage for the dataset here
__lowercase:		List[str]    						=  ""

# TODO: Add the licence for the dataset here if you can find it
__lowercase:		List[Any]    						=  ""

# TODO: Add link to the official dataset URLs here
# The HuggingFace Datasets library doesn't host the datasets but only points to the original files.
# This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)
__lowercase:		List[str]    						=  {
    "first_domain": "https://huggingface.co/great-new-dataset-first_domain.zip",
    "second_domain": "https://huggingface.co/great-new-dataset-second_domain.zip",
}







class 			UpperCAmelCase			(							datasets.GeneratorBasedBuilder):
 _lowerCamelCase			:       List[str]            =       datasets.Version('1.1.0')

 # This is an example of a dataset with multiple configurations.
 # If you don't want/need to define several sub-sets in your dataset,
 # just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes.

 # If you need to make complex sub-parts in the datasets with configurable options
 # You can create your own builder configuration class to store attribute, inheriting from datasets.BuilderConfig
 # BUILDER_CONFIG_CLASS = MyBuilderConfig

 # You will be able to load one or the other configurations in the following list with
 # data = datasets.load_dataset('my_dataset', 'first_domain')
 # data = datasets.load_dataset('my_dataset', 'second_domain')
 _lowerCamelCase			:       Dict            =       [
     datasets.BuilderConfig(name='first_domain'		,      version=SCREAMING_SNAKE_CASE__		,      description='This part of my dataset covers a first domain'),
     datasets.BuilderConfig(name='second_domain'		,      version=SCREAMING_SNAKE_CASE__		,      description='This part of my dataset covers a second domain'),
 ]

 _lowerCamelCase			:       Any            =       'first_domain'  # It's not mandatory to have a default configuration. Just use one if it make sense.

 def 		lowercase_    (			self			:						List[str]       ):





    """simple docstring"""



    if self.config.name == "first_domain":  # This is the name of the configuration selected in BUILDER_CONFIGS above
       UpperCamelCase__			    =    datasets.Features(
           {
               "sentence": datasets.Value("string"       ),
               "option1": datasets.Value("string"       ),
               "answer": datasets.Value("string"       )
               # These are the features of your dataset like images, labels ...
           }       )
    else:  # This is an example to show how to have different features for "first_domain" and "second_domain"
       UpperCamelCase__			    =    datasets.Features(
           {
               "sentence": datasets.Value("string"       ),
               "option2": datasets.Value("string"       ),
               "second_domain_answer": datasets.Value("string"       )
               # These are the features of your dataset like images, labels ...
           }       )
    return datasets.DatasetInfo(
        # This is the description that will appear on the datasets page.
        description=_DESCRIPTION,       features=a_,       homepage=_HOMEPAGE,       license=_LICENSE,       citation=_CITATION,       )

 def 		lowercase_    (			self			:						Any,       a_			:						Union[str, Any]       ):





    """simple docstring"""



    UpperCamelCase__			    =    _URLS[self.config.name]
    UpperCamelCase__			    =    dl_manager.download_and_extract(a_       )
    return [
        datasets.SplitGenerator(
            name=datasets.Split.TRAIN,       gen_kwargs={
                "filepath": os.path.join(a_,       "train.jsonl"       ),
                "split": "train",
            },       ),
        datasets.SplitGenerator(
            name=datasets.Split.VALIDATION,       gen_kwargs={
                "filepath": os.path.join(a_,       "dev.jsonl"       ),
                "split": "dev",
            },       ),
        datasets.SplitGenerator(
            name=datasets.Split.TEST,       gen_kwargs={
                "filepath": os.path.join(a_,       "test.jsonl"       ),
                "split": "test"
            },       ),
    ]

 def 		lowercase_    (			self			:						str,       a_			:						Optional[Any],       a_			:						Tuple       ):





    """simple docstring"""



    with open(a_,       encoding="utf-8"       ) as f:
       for key, row in enumerate(a_       ):
          UpperCamelCase__			    =    json.loads(a_       )
          if self.config.name == "first_domain":
             # Yields examples as (key, example) tuples
             yield key, {
                 "sentence": data["sentence"],
                 "option1": data["option1"],
                 "answer": "" if split == "test" else data["answer"],
             }
          else:
             yield key, {
                 "sentence": data["sentence"],
                 "option2": data["option2"],
                 "second_domain_answer": "" if split == "test" else data["second_domain_answer"],
             }