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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# calculator.py
|
| 2 |
+
import re
|
| 3 |
+
import math
|
| 4 |
+
import operator
|
| 5 |
+
from typing import List, Dict, Optional
|
| 6 |
+
from contextlib import contextmanager
|
| 7 |
+
import signal
|
| 8 |
+
from functools import reduce
|
| 9 |
+
from fractions import Fraction
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# TIMEOUT
|
| 13 |
+
@contextmanager
|
| 14 |
+
def timeout(duration: int = 1):
|
| 15 |
+
def handler(signum, frame):
|
| 16 |
+
raise TimeoutError(f"Timeout after {duration}s")
|
| 17 |
+
|
| 18 |
+
signal.signal(signal.SIGALRM, handler)
|
| 19 |
+
signal.alarm(duration)
|
| 20 |
+
try:
|
| 21 |
+
yield
|
| 22 |
+
finally:
|
| 23 |
+
signal.alarm(0)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
# SAFE EVAL
|
| 27 |
+
def safe_eval(expr: str) -> Optional[float]:
|
| 28 |
+
expr = expr.strip().replace(",", "").replace("^", "**")
|
| 29 |
+
|
| 30 |
+
# SECURITY: BLOCK __class__, .., .x
|
| 31 |
+
if ".." in expr or "__" in expr:
|
| 32 |
+
return None
|
| 33 |
+
if re.search(r'\.\w', expr) and not re.search(r'\d\.', expr):
|
| 34 |
+
return None
|
| 35 |
+
|
| 36 |
+
# BLOCK GIANT EXPONENTS
|
| 37 |
+
if "**" in expr:
|
| 38 |
+
try:
|
| 39 |
+
_, exp_str = expr.split("**", 1)
|
| 40 |
+
exp = float(re.split(r'[\s+\-*/)]', exp_str)[0])
|
| 41 |
+
if abs(exp) > 20:
|
| 42 |
+
return None
|
| 43 |
+
except:
|
| 44 |
+
pass
|
| 45 |
+
|
| 46 |
+
# BLOCK SCIENTIFIC NOTATION OVERFLOW
|
| 47 |
+
sci_match = re.search(r'\d+e[+\-]?\d+', expr, re.IGNORECASE)
|
| 48 |
+
if sci_match:
|
| 49 |
+
try:
|
| 50 |
+
exp = int(re.search(r'e([+\-]?\d+)', sci_match.group(0), re.IGNORECASE).group(1))
|
| 51 |
+
if abs(exp) > 50:
|
| 52 |
+
return None
|
| 53 |
+
except:
|
| 54 |
+
return None
|
| 55 |
+
|
| 56 |
+
# FRACTION SIMPLIFICATION
|
| 57 |
+
if "/" in expr and not re.search(r'//', expr):
|
| 58 |
+
try:
|
| 59 |
+
parts = [p.strip() for p in expr.split("/", 1)]
|
| 60 |
+
if len(parts) == 2 and parts[0].isdigit() and parts[1].isdigit():
|
| 61 |
+
return float(Fraction(int(parts[0]), int(parts[1])))
|
| 62 |
+
except:
|
| 63 |
+
pass
|
| 64 |
+
|
| 65 |
+
# ALLOW % (modulo)
|
| 66 |
+
expr = expr.replace("%", " % ")
|
| 67 |
+
|
| 68 |
+
if not re.match(r'^[0-9+\-*/().%\s\*\^]+$', expr):
|
| 69 |
+
return None
|
| 70 |
+
|
| 71 |
+
try:
|
| 72 |
+
with timeout(1):
|
| 73 |
+
result = eval(expr, {"__builtins__": {}})
|
| 74 |
+
return float(result)
|
| 75 |
+
except:
|
| 76 |
+
return None
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
# EXTRACT << (GREEDY RIGHTMOST)
|
| 80 |
+
def extract_calc(text: str) -> Optional[str]:
|
| 81 |
+
match = re.search(r'<<([^>]*)(?:>>|$)', text)
|
| 82 |
+
if not match:
|
| 83 |
+
return None
|
| 84 |
+
expr = match.group(1).strip()
|
| 85 |
+
return expr if expr else None
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# VARIABLE REPLACEMENT (longest first)
|
| 89 |
+
def substitute_variables(expr: str, context: Dict[str, float]) -> str:
|
| 90 |
+
for var in sorted(context.keys(), key=len, reverse=True):
|
| 91 |
+
expr = re.sub(rf'\b{re.escape(var)}\b', str(context[var]), expr)
|
| 92 |
+
return expr
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
# NESTED FUNCTION PARSER
|
| 96 |
+
def parse_nested_func(expr: str, allowed_funcs: set = None) -> Optional[float]:
|
| 97 |
+
if allowed_funcs is None:
|
| 98 |
+
allowed_funcs = {"sqrt", "log", "pow", "max", "min", "abs", "sin", "cos", "tan", "exp"}
|
| 99 |
+
|
| 100 |
+
def eval_inner(inner: str) -> float:
|
| 101 |
+
inner = inner.strip()
|
| 102 |
+
if inner.startswith("(") and inner.endswith(")"):
|
| 103 |
+
inner = inner[1:-1]
|
| 104 |
+
return parse_nested_func(inner, allowed_funcs) or safe_eval(inner) or 0.0
|
| 105 |
+
|
| 106 |
+
match = re.match(r'^([a-zA-Z_]\w*)\((.+)\)$', expr.strip())
|
| 107 |
+
if not match:
|
| 108 |
+
return None
|
| 109 |
+
func_name, args_str = match.groups()
|
| 110 |
+
|
| 111 |
+
if func_name not in allowed_funcs:
|
| 112 |
+
return None
|
| 113 |
+
|
| 114 |
+
# Split top-level commas
|
| 115 |
+
args = []
|
| 116 |
+
depth = 0
|
| 117 |
+
current = ""
|
| 118 |
+
for char in args_str:
|
| 119 |
+
if char == "," and depth == 0:
|
| 120 |
+
args.append(current)
|
| 121 |
+
current = ""
|
| 122 |
+
else:
|
| 123 |
+
current += char
|
| 124 |
+
if char == "(": depth += 1
|
| 125 |
+
if char == ")": depth -= 1
|
| 126 |
+
if current:
|
| 127 |
+
args.append(current)
|
| 128 |
+
|
| 129 |
+
try:
|
| 130 |
+
arg_vals = [eval_inner(a) for a in args]
|
| 131 |
+
|
| 132 |
+
# BLOCK GIANT pow() AND exp()
|
| 133 |
+
if func_name == "pow" and len(arg_vals) >= 2 and abs(arg_vals[1]) > 20:
|
| 134 |
+
return None
|
| 135 |
+
if func_name == "exp" and arg_vals and abs(arg_vals[0]) > 20:
|
| 136 |
+
return None
|
| 137 |
+
|
| 138 |
+
func_map = {
|
| 139 |
+
"sqrt": lambda x: math.sqrt(x[0]),
|
| 140 |
+
"log": lambda x: math.log(x[0], x[1]) if len(x) > 1 else math.log(x[0]),
|
| 141 |
+
"pow": lambda x: x[0] ** x[1],
|
| 142 |
+
"max": lambda x: max(x),
|
| 143 |
+
"min": lambda x: min(x),
|
| 144 |
+
"abs": lambda x: abs(x[0]),
|
| 145 |
+
"sin": lambda x: math.sin(x[0]),
|
| 146 |
+
"cos": lambda x: math.cos(x[0]),
|
| 147 |
+
"tan": lambda x: math.tan(x[0]),
|
| 148 |
+
"exp": lambda x: math.exp(x[0]),
|
| 149 |
+
}
|
| 150 |
+
return func_map[func_name](arg_vals)
|
| 151 |
+
except:
|
| 152 |
+
return None
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
# === SEQUENCE + RANGE (NESTED) ===
|
| 156 |
+
def parse_range(range_str: str) -> List[float]:
|
| 157 |
+
match = re.match(r'(-?\d+)\.\.(-?\d+)', range_str.strip())
|
| 158 |
+
if not match:
|
| 159 |
+
return []
|
| 160 |
+
start, end = map(int, match.groups())
|
| 161 |
+
step = 1 if start <= end else -1
|
| 162 |
+
return list(range(start, end + step, step))
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def evaluate_sequence(expr: str) -> Optional[float]:
|
| 166 |
+
match = re.match(r'(sum|prod|mean)\((.*)\)', expr.replace(" ", ""))
|
| 167 |
+
if not match:
|
| 168 |
+
return None
|
| 169 |
+
op, args_str = match.groups()
|
| 170 |
+
|
| 171 |
+
def parse_arg(arg: str):
|
| 172 |
+
arg = arg.strip()
|
| 173 |
+
if ".." in arg:
|
| 174 |
+
return parse_range(arg)
|
| 175 |
+
val = parse_nested_func(arg) or safe_eval(arg)
|
| 176 |
+
return [val] if val is not None else []
|
| 177 |
+
|
| 178 |
+
args = []
|
| 179 |
+
depth = 0
|
| 180 |
+
current = ""
|
| 181 |
+
for char in args_str:
|
| 182 |
+
if char == "," and depth == 0:
|
| 183 |
+
args.extend(parse_arg(current))
|
| 184 |
+
current = ""
|
| 185 |
+
else:
|
| 186 |
+
current += char
|
| 187 |
+
if char == "(": depth += 1
|
| 188 |
+
if char == ")": depth -= 1
|
| 189 |
+
if current:
|
| 190 |
+
args.extend(parse_arg(current))
|
| 191 |
+
|
| 192 |
+
if not args:
|
| 193 |
+
return None
|
| 194 |
+
|
| 195 |
+
if op == "sum": return sum(args)
|
| 196 |
+
if op == "prod": return reduce(operator.mul, args, 1)
|
| 197 |
+
if op == "mean": return sum(args) / len(args)
|
| 198 |
+
return None
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
# CALCULATOR
|
| 202 |
+
def calculate(expr: str, context: Dict[str, float] = None) -> Optional[str]:
|
| 203 |
+
if context is None:
|
| 204 |
+
context = {}
|
| 205 |
+
expr = substitute_variables(expr, context)
|
| 206 |
+
|
| 207 |
+
seq = evaluate_sequence(expr)
|
| 208 |
+
if seq is not None:
|
| 209 |
+
return f"{expr}={seq}>>"
|
| 210 |
+
|
| 211 |
+
func = parse_nested_func(expr)
|
| 212 |
+
if func is not None:
|
| 213 |
+
return f"{expr}={func}>>"
|
| 214 |
+
|
| 215 |
+
basic = safe_eval(expr)
|
| 216 |
+
if basic is not None:
|
| 217 |
+
return f"{expr}={basic}>>"
|
| 218 |
+
|
| 219 |
+
return None
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
# PUBLIC API
|
| 223 |
+
def use_calculator(text: str, context: Dict[str, float] = None) -> Optional[str]:
|
| 224 |
+
expr = extract_calc(text)
|
| 225 |
+
if not expr:
|
| 226 |
+
return None
|
| 227 |
+
return calculate(expr, context)
|
| 228 |
+
|