Upload utils.py with huggingface_hub
Browse files3 unmodified lines45678972 unmodified lines8283843 unmodified linesimport pkg_resourcesclass Singleton(type):_instances = {}72 unmodified linesreturn Trueexcept ImportError:return False3 unmodified lines456789101172 unmodified lines848586878889909192939495969798991001011021031041051061071081091101111121131141153 unmodified linesimport pkg_resourcesfrom .text_utils import is_made_of_sub_stringsclass Singleton(type):_instances = {}72 unmodified linesreturn Trueexcept ImportError:return Falsedef safe_eval(expression: str, context: dict, allowed_tokens: list) -> any:"""Evaluates a given expression in a restricted environment, allowing only specified tokens and context variables.Args:expression (str): The expression to evaluate.context (dict): A dictionary mapping variable names to their values, whichcan be used in the expression.allowed_tokens (list): A list of strings representing allowed tokens (such asoperators, function names, etc.) that can be used in the expression.Returns:any: The result of evaluating the expression.Raises:ValueError: If the expression contains tokens not in the allowed list or context keys.Note:This function should be used carefully, as it employs `eval`, which canexecute arbitrary code. The function attempts to mitigate security risksby restricting the available tokens and not exposing built-in functions."""allowd_sub_strings = list(context.keys()) + allowed_tokensif is_made_of_sub_strings(expression, allowd_sub_strings):return eval(expression, {"__builtins__": {}}, context)raise ValueError(f"The expression '{expression}' can not be evaluated because it contains tokens outside the allowed list of {allowd_sub_strings}.")
utils.py+31