
'''simple docstring'''
import ast
import difflib
from collections.abc import Mapping
from typing import Any, Callable, Dict






class       UpperCAmelCase_ (		snake_case__    ):
 pass


def   UpperCamelCase_   (		__SCREAMING_SNAKE_CASE,						__SCREAMING_SNAKE_CASE,						__SCREAMING_SNAKE_CASE=None,						__SCREAMING_SNAKE_CASE=False				):
    """simple docstring"""






    try:
        snake_case_       :			int   	=  ast.parse(__UpperCAmelCase				)
    except SyntaxError as e:
        print("The code generated by the agent is not valid.\n",						__UpperCAmelCase				)
        return
    if state is None:
        snake_case_       :			List[str]   	=  {}
    snake_case_       :			Union[str, Any]   	=  None
    for idx, node in enumerate(expression.body				):
        try:
            snake_case_       :			str   	=  evaluate_ast(__UpperCAmelCase,						__UpperCAmelCase,						__UpperCAmelCase				)
        except InterpretorError as e:
            snake_case_       :			Optional[int]   	=  f'Evaluation of the code stopped at line {idx} before the end because of the following error'
            if chat_mode:
                msg += (
                    f'. Copy paste the following error message and send it back to the agent:\nI get an error: \'{e}\''
                )
            else:
                msg += f':\n{e}'
            print(__UpperCAmelCase				)
            break
        if line_result is not None:
            snake_case_       :			Optional[Any]   	=  line_result

    return result

def   UpperCamelCase_   (		__SCREAMING_SNAKE_CASE,						__SCREAMING_SNAKE_CASE,						__SCREAMING_SNAKE_CASE				):
    """simple docstring"""






    if isinstance(__UpperCAmelCase,						ast.Assign				):
        # Assignement -> we evaluate the assignement which should update the state
        # We return the variable assigned as it may be used to determine the final result.
        return evaluate_assign(__UpperCAmelCase,						__UpperCAmelCase,						__UpperCAmelCase				)
    elif isinstance(__UpperCAmelCase,						ast.Call				):
        # Function call -> we return the value of the function call
        return evaluate_call(__UpperCAmelCase,						__UpperCAmelCase,						__UpperCAmelCase				)
    elif isinstance(__UpperCAmelCase,						ast.Constant				):
        # Constant -> just return the value
        return expression.value
    elif isinstance(__UpperCAmelCase,						ast.Dict				):
        # Dict -> evaluate all keys and values
        snake_case_       :			Tuple   	=  [evaluate_ast(__UpperCAmelCase,						__UpperCAmelCase,						__UpperCAmelCase				) for k in expression.keys]
        snake_case_       :			Tuple   	=  [evaluate_ast(__UpperCAmelCase,						__UpperCAmelCase,						__UpperCAmelCase				) for v in expression.values]
        return dict(zip(__UpperCAmelCase,						__UpperCAmelCase				)				)
    elif isinstance(__UpperCAmelCase,						ast.Expr				):
        # Expression -> evaluate the content
        return evaluate_ast(expression.value,						__UpperCAmelCase,						__UpperCAmelCase				)
    elif isinstance(__UpperCAmelCase,						ast.For				):
        # For loop -> execute the loop
        return evaluate_for(__UpperCAmelCase,						__UpperCAmelCase,						__UpperCAmelCase				)
    elif isinstance(__UpperCAmelCase,						ast.FormattedValue				):
        # Formatted value (part of f-string) -> evaluate the content and return
        return evaluate_ast(expression.value,						__UpperCAmelCase,						__UpperCAmelCase				)
    elif isinstance(__UpperCAmelCase,						ast.If				):
        # If -> execute the right branch
        return evaluate_if(__UpperCAmelCase,						__UpperCAmelCase,						__UpperCAmelCase				)
    elif hasattr(__UpperCAmelCase,						"Index"				) and isinstance(__UpperCAmelCase,						ast.Index				):
        return evaluate_ast(expression.value,						__UpperCAmelCase,						__UpperCAmelCase				)
    elif isinstance(__UpperCAmelCase,						ast.JoinedStr				):
        return "".join([str(evaluate_ast(__UpperCAmelCase,						__UpperCAmelCase,						__UpperCAmelCase				)				) for v in expression.values]				)
    elif isinstance(__UpperCAmelCase,						ast.List				):
        # List -> evaluate all elements
        return [evaluate_ast(__UpperCAmelCase,						__UpperCAmelCase,						__UpperCAmelCase				) for elt in expression.elts]
    elif isinstance(__UpperCAmelCase,						ast.Name				):
        # Name -> pick up the value in the state
        return evaluate_name(__UpperCAmelCase,						__UpperCAmelCase,						__UpperCAmelCase				)
    elif isinstance(__UpperCAmelCase,						ast.Subscript				):
        # Subscript -> return the value of the indexing
        return evaluate_subscript(__UpperCAmelCase,						__UpperCAmelCase,						__UpperCAmelCase				)
    else:
        # For now we refuse anything else. Let's add things as we need them.
        raise InterpretorError(f'{expression.__class__.__name__} is not supported.'				)

def   UpperCamelCase_   (		__SCREAMING_SNAKE_CASE,						__SCREAMING_SNAKE_CASE,						__SCREAMING_SNAKE_CASE				):
    """simple docstring"""






    snake_case_       :			List[Any]   	=  assign.targets
    snake_case_       :			Dict   	=  evaluate_ast(assign.value,						__UpperCAmelCase,						__UpperCAmelCase				)

    if len(__UpperCAmelCase				) == 1:
        snake_case_       :			List[Any]   	=  result
    else:
        if len(__UpperCAmelCase				) != len(__UpperCAmelCase				):
            raise InterpretorError(f'Expected {len(__UpperCAmelCase				)} values but got {len(__UpperCAmelCase				)}.'				)
        for var_name, r in zip(__UpperCAmelCase,						__UpperCAmelCase				):
            snake_case_       :			Optional[int]   	=  r
    return result

def   UpperCamelCase_   (		__SCREAMING_SNAKE_CASE,						__SCREAMING_SNAKE_CASE,						__SCREAMING_SNAKE_CASE				):
    """simple docstring"""






    if not isinstance(call.func,						ast.Name				):
        raise InterpretorError(
            f'It is not permitted to evaluate other functions than the provided tools (tried to execute {call.func} of '
            f'type {type(call.func				)}.'				)
    snake_case_       :			Tuple   	=  call.func.id
    if func_name not in tools:
        raise InterpretorError(
            f'It is not permitted to evaluate other functions than the provided tools (tried to execute {call.func.id}).'				)

    snake_case_       :			List[Any]   	=  tools[func_name]
    # Todo deal with args
    snake_case_       :			Union[str, Any]   	=  [evaluate_ast(__UpperCAmelCase,						__UpperCAmelCase,						__UpperCAmelCase				) for arg in call.args]
    snake_case_       :			Optional[int]   	=  {keyword.arg: evaluate_ast(keyword.value,						__UpperCAmelCase,						__UpperCAmelCase				) for keyword in call.keywords}
    return func(*__UpperCAmelCase,						**__UpperCAmelCase				)

def   UpperCamelCase_   (		__SCREAMING_SNAKE_CASE,						__SCREAMING_SNAKE_CASE,						__SCREAMING_SNAKE_CASE				):
    """simple docstring"""






    snake_case_       :			Union[str, Any]   	=  evaluate_ast(subscript.slice,						__UpperCAmelCase,						__UpperCAmelCase				)
    snake_case_       :			Optional[int]   	=  evaluate_ast(subscript.value,						__UpperCAmelCase,						__UpperCAmelCase				)
    if isinstance(__UpperCAmelCase,						(list, tuple)				):
        return value[int(__UpperCAmelCase				)]
    if index in value:
        return value[index]
    if isinstance(__UpperCAmelCase,						__UpperCAmelCase				) and isinstance(__UpperCAmelCase,						__UpperCAmelCase				):
        snake_case_       :			Dict   	=  difflib.get_close_matches(__UpperCAmelCase,						list(value.keys()				)				)
        if len(__UpperCAmelCase				) > 0:
            return value[close_matches[0]]

    raise InterpretorError(f'Could not index {value} with \'{index}\'.'				)

def   UpperCamelCase_   (		__SCREAMING_SNAKE_CASE,						__SCREAMING_SNAKE_CASE,						__SCREAMING_SNAKE_CASE				):
    """simple docstring"""






    if name.id in state:
        return state[name.id]
    snake_case_       :			Dict   	=  difflib.get_close_matches(name.id,						list(state.keys()				)				)
    if len(__UpperCAmelCase				) > 0:
        return state[close_matches[0]]
    raise InterpretorError(f'The variable `{name.id}` is not defined.'				)

def   UpperCamelCase_   (		__SCREAMING_SNAKE_CASE,						__SCREAMING_SNAKE_CASE,						__SCREAMING_SNAKE_CASE				):
    """simple docstring"""






    if len(condition.ops				) > 1:
        raise InterpretorError("Cannot evaluate conditions with multiple operators"				)

    snake_case_       :			Any   	=  evaluate_ast(condition.left,						__UpperCAmelCase,						__UpperCAmelCase				)
    snake_case_       :			str   	=  condition.ops[0]
    snake_case_       :			Union[str, Any]   	=  evaluate_ast(condition.comparators[0],						__UpperCAmelCase,						__UpperCAmelCase				)

    if isinstance(__UpperCAmelCase,						ast.Eq				):
        return left == right
    elif isinstance(__UpperCAmelCase,						ast.NotEq				):
        return left != right
    elif isinstance(__UpperCAmelCase,						ast.Lt				):
        return left < right
    elif isinstance(__UpperCAmelCase,						ast.LtE				):
        return left <= right
    elif isinstance(__UpperCAmelCase,						ast.Gt				):
        return left > right
    elif isinstance(__UpperCAmelCase,						ast.GtE				):
        return left >= right
    elif isinstance(__UpperCAmelCase,						ast.Is				):
        return left is right
    elif isinstance(__UpperCAmelCase,						ast.IsNot				):
        return left is not right
    elif isinstance(__UpperCAmelCase,						ast.In				):
        return left in right
    elif isinstance(__UpperCAmelCase,						ast.NotIn				):
        return left not in right
    else:
        raise InterpretorError(f'Operator not supported: {comparator}'				)

def   UpperCamelCase_   (		__SCREAMING_SNAKE_CASE,						__SCREAMING_SNAKE_CASE,						__SCREAMING_SNAKE_CASE				):
    """simple docstring"""






    snake_case_       :			Tuple   	=  None
    if evaluate_condition(if_statement.test,						__UpperCAmelCase,						__UpperCAmelCase				):
        for line in if_statement.body:
            snake_case_       :			Union[str, Any]   	=  evaluate_ast(__UpperCAmelCase,						__UpperCAmelCase,						__UpperCAmelCase				)
            if line_result is not None:
                snake_case_       :			Union[str, Any]   	=  line_result
    else:
        for line in if_statement.orelse:
            snake_case_       :			Optional[Any]   	=  evaluate_ast(__UpperCAmelCase,						__UpperCAmelCase,						__UpperCAmelCase				)
            if line_result is not None:
                snake_case_       :			int   	=  line_result
    return result


def   UpperCamelCase_   (		__SCREAMING_SNAKE_CASE,						__SCREAMING_SNAKE_CASE,						__SCREAMING_SNAKE_CASE				):
    """simple docstring"""






    snake_case_       :			Optional[Any]   	=  None
    snake_case_       :			Union[str, Any]   	=  evaluate_ast(for_loop.iter,						__UpperCAmelCase,						__UpperCAmelCase				)
    for counter in iterator:
        snake_case_       :			Dict   	=  counter
        for expression in for_loop.body:
            snake_case_       :			Tuple   	=  evaluate_ast(__UpperCAmelCase,						__UpperCAmelCase,						__UpperCAmelCase				)
            if line_result is not None:
                snake_case_       :			str   	=  line_result
    return result









"""simple docstring"""







from sklearn.metrics import precision_score

import datasets


UpperCAmelCase:   Optional[Any]       			=							"""
Precision 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:
Precision = TP / (TP + FP)
where 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).
"""


UpperCAmelCase:   Union[str, Any]       			=							"""
Args:
    predictions (`list` of `int`): Predicted class labels.
    references (`list` of `int`): Actual class labels.
    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.
    pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.
    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'`.

        - '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.
        - '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. This option 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 (`int` or `string`): Sets the value to return when there is a zero division. Defaults to 'warn'.

        - 0: Returns 0 when there is a zero division.
        - 1: Returns 1 when there is a zero division.
        - 'warn': Raises warnings and then returns 0 when there is a zero division.

Returns:
    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.

Examples:

    Example 1-A simple binary example
        >>> precision_metric = datasets.load_metric(\"precision\")
        >>> results = precision_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])
        >>> print(results)
        {'precision': 0.5}

    Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.
        >>> precision_metric = datasets.load_metric(\"precision\")
        >>> results = precision_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)
        >>> print(round(results['precision'], 2))
        0.67

    Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.
        >>> precision_metric = datasets.load_metric(\"precision\")
        >>> 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])
        >>> print(results)
        {'precision': 0.23529411764705882}

    Example 4-A multiclass example, with different values for the `average` input.
        >>> predictions = [0, 2, 1, 0, 0, 1]
        >>> references = [0, 1, 2, 0, 1, 2]
        >>> results = precision_metric.compute(predictions=predictions, references=references, average='macro')
        >>> print(results)
        {'precision': 0.2222222222222222}
        >>> results = precision_metric.compute(predictions=predictions, references=references, average='micro')
        >>> print(results)
        {'precision': 0.3333333333333333}
        >>> results = precision_metric.compute(predictions=predictions, references=references, average='weighted')
        >>> print(results)
        {'precision': 0.2222222222222222}
        >>> results = precision_metric.compute(predictions=predictions, references=references, average=None)
        >>> print([round(res, 2) for res in results['precision']])
        [0.67, 0.0, 0.0]
"""


UpperCAmelCase:   List[str]       			=							"""
@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    UpperCamelCase     (			datasets.Metric    ):




	"""simple docstring"""






	def 					lowerCamelCase__ (			self					):
			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 					lowerCamelCase__ (			self							,UpperCAmelCase_							,UpperCAmelCase_							,UpperCAmelCase_=None							,UpperCAmelCase_=1							,UpperCAmelCase_="binary"							,UpperCAmelCase_=None							,UpperCAmelCase_="warn"							,):
			_lowercase							:      int			=					precision_score(
			    UpperCAmelCase_							,UpperCAmelCase_							,labels=UpperCAmelCase_							,pos_label=UpperCAmelCase_							,average=UpperCAmelCase_							,sample_weight=UpperCAmelCase_							,zero_division=UpperCAmelCase_							,)
			return {"precision": float(UpperCAmelCase_					) if score.size == 1 else score}



