



"""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 ast
import difflib
from collections.abc import Mapping
from typing import Any, Callable, Dict





class    UpperCamelCase     (			snake_case    ):




	"""simple docstring"""
	pass







def       __SCREAMING_SNAKE_CASE      (   __UpperCAmelCase					,							__UpperCAmelCase					,							__UpperCAmelCase=None					,							__UpperCAmelCase=False	):
		try:
				_lowercase							:      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:
				_lowercase							:      List[str]			=					{}
		_lowercase							:      Union[str, Any]			=					None
		for idx, node in enumerate(expression.body	):
				try:
						_lowercase							:      str			=					evaluate_ast(__UpperCAmelCase					,							__UpperCAmelCase					,							__UpperCAmelCase	)
				except InterpretorError as e:
						_lowercase							:      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:
						_lowercase							:      Optional[Any]			=					line_result

		return result


def       __SCREAMING_SNAKE_CASE      (   __UpperCAmelCase					,							__UpperCAmelCase					,							__UpperCAmelCase	):
		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
				_lowercase							:      Tuple			=					[evaluate_ast(__UpperCAmelCase					,							__UpperCAmelCase					,							__UpperCAmelCase	) for k in expression.keys]
				_lowercase							:      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       __SCREAMING_SNAKE_CASE      (   __UpperCAmelCase					,							__UpperCAmelCase					,							__UpperCAmelCase	):
		_lowercase							:      List[Any]			=					assign.targets
		_lowercase							:      Dict			=					evaluate_ast(assign.value					,							__UpperCAmelCase					,							__UpperCAmelCase	)

		if len(__UpperCAmelCase	) == 1:
				_lowercase							:      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	):
						_lowercase							:      Optional[int]			=					r
		return result


def       __SCREAMING_SNAKE_CASE      (   __UpperCAmelCase					,							__UpperCAmelCase					,							__UpperCAmelCase	):
		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	)}."""	)
		_lowercase							:      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})."""	)

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


def       __SCREAMING_SNAKE_CASE      (   __UpperCAmelCase					,							__UpperCAmelCase					,							__UpperCAmelCase	):
		_lowercase							:      Union[str, Any]			=					evaluate_ast(subscript.slice					,							__UpperCAmelCase					,							__UpperCAmelCase	)
		_lowercase							:      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	):
				_lowercase							:      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       __SCREAMING_SNAKE_CASE      (   __UpperCAmelCase					,							__UpperCAmelCase					,							__UpperCAmelCase	):
		if name.id in state:
				return state[name.id]
		_lowercase							:      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       __SCREAMING_SNAKE_CASE      (   __UpperCAmelCase					,							__UpperCAmelCase					,							__UpperCAmelCase	):
		if len(condition.ops	) > 1:
				raise InterpretorError("""Cannot evaluate conditions with multiple operators"""	)

		_lowercase							:      Any			=					evaluate_ast(condition.left					,							__UpperCAmelCase					,							__UpperCAmelCase	)
		_lowercase							:      str			=					condition.ops[0]
		_lowercase							:      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       __SCREAMING_SNAKE_CASE      (   __UpperCAmelCase					,							__UpperCAmelCase					,							__UpperCAmelCase	):
		_lowercase							:      Tuple			=					None
		if evaluate_condition(if_statement.test					,							__UpperCAmelCase					,							__UpperCAmelCase	):
				for line in if_statement.body:
						_lowercase							:      Union[str, Any]			=					evaluate_ast(__UpperCAmelCase					,							__UpperCAmelCase					,							__UpperCAmelCase	)
						if line_result is not None:
								_lowercase							:      Union[str, Any]			=					line_result
		else:
				for line in if_statement.orelse:
						_lowercase							:      Optional[Any]			=					evaluate_ast(__UpperCAmelCase					,							__UpperCAmelCase					,							__UpperCAmelCase	)
						if line_result is not None:
								_lowercase							:      int			=					line_result
		return result


def       __SCREAMING_SNAKE_CASE      (   __UpperCAmelCase					,							__UpperCAmelCase					,							__UpperCAmelCase	):
		_lowercase							:      Optional[Any]			=					None
		_lowercase							:      Union[str, Any]			=					evaluate_ast(for_loop.iter					,							__UpperCAmelCase					,							__UpperCAmelCase	)
		for counter in iterator:
				_lowercase							:      Dict			=					counter
				for expression in for_loop.body:
						_lowercase							:      Tuple			=					evaluate_ast(__UpperCAmelCase					,							__UpperCAmelCase					,							__UpperCAmelCase	)
						if line_result is not None:
								_lowercase							:      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}



