Upload utils.py with huggingface_hub
Browse files
utils.py
CHANGED
@@ -4,6 +4,8 @@ from typing import Any, Dict
|
|
4 |
|
5 |
import pkg_resources
|
6 |
|
|
|
|
|
7 |
|
8 |
class Singleton(type):
|
9 |
_instances = {}
|
@@ -82,3 +84,32 @@ def is_module_available(module_name):
|
|
82 |
return True
|
83 |
except ImportError:
|
84 |
return False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
4 |
|
5 |
import pkg_resources
|
6 |
|
7 |
+
from .text_utils import is_made_of_sub_strings
|
8 |
+
|
9 |
|
10 |
class Singleton(type):
|
11 |
_instances = {}
|
|
|
84 |
return True
|
85 |
except ImportError:
|
86 |
return False
|
87 |
+
|
88 |
+
|
89 |
+
def safe_eval(expression: str, context: dict, allowed_tokens: list) -> any:
|
90 |
+
"""Evaluates a given expression in a restricted environment, allowing only specified tokens and context variables.
|
91 |
+
|
92 |
+
Args:
|
93 |
+
expression (str): The expression to evaluate.
|
94 |
+
context (dict): A dictionary mapping variable names to their values, which
|
95 |
+
can be used in the expression.
|
96 |
+
allowed_tokens (list): A list of strings representing allowed tokens (such as
|
97 |
+
operators, function names, etc.) that can be used in the expression.
|
98 |
+
|
99 |
+
Returns:
|
100 |
+
any: The result of evaluating the expression.
|
101 |
+
|
102 |
+
Raises:
|
103 |
+
ValueError: If the expression contains tokens not in the allowed list or context keys.
|
104 |
+
|
105 |
+
Note:
|
106 |
+
This function should be used carefully, as it employs `eval`, which can
|
107 |
+
execute arbitrary code. The function attempts to mitigate security risks
|
108 |
+
by restricting the available tokens and not exposing built-in functions.
|
109 |
+
"""
|
110 |
+
allowd_sub_strings = list(context.keys()) + allowed_tokens
|
111 |
+
if is_made_of_sub_strings(expression, allowd_sub_strings):
|
112 |
+
return eval(expression, {"__builtins__": {}}, context)
|
113 |
+
raise ValueError(
|
114 |
+
f"The expression '{expression}' can not be evaluated because it contains tokens outside the allowed list of {allowd_sub_strings}."
|
115 |
+
)
|