File size: 1,863 Bytes
2f05f1b
 
 
 
 
 
 
 
 
 
 
 
 
 
80566e9
2f05f1b
 
 
bc74ce4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdd6ccc
 
 
 
 
 
 
2f05f1b
 
 
 
80566e9
2f05f1b
 
 
 
 
 
 
80566e9
2f05f1b
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
description = """
Enter a math formula using the following operators and functions:

**Operators:** +, -, *, /, **, %, <, <=, ==, !=, >=, >, &, |, ~

**Functions:** sin, cos, tan, arcsin, arccos, arctan, arctan2, sinh, cosh, tanh, arcsinh, arccosh, arctanh, log, log10, log1p, exp, expm1, sqrt, abs, where, complex, real, imag, conj

**Examples:**
- exp(2) + sqrt(9)
- log(10) / 2
- where(5 > 2, 10, 0)
- sin(3.14/2) * 2
"""

import gradio as gr
import numexpr

def safe_math_eval(expression: str) -> float:
    """Enter a math formula using the supported operators and functions.

**Supported Operators:**
- `+` (addition)
- `-` (subtraction)
- `*` (multiplication)
- `/` (division)
- `**` (power)
- `%` (modulus)
- `<`, `<=`, `==`, `!=`, `>=`, `>` (comparisons)
- `&`, `|`, `~` (bitwise and logical operators)

**Supported Functions:**
- Trigonometric: `sin`, `cos`, `tan`, `arcsin`, `arccos`, `arctan`, `arctan2`
- Hyperbolic: `sinh`, `cosh`, `tanh`, `arcsinh`, `arccosh`, `arctanh`
- Logarithmic & Exponential: `log`, `log10`, `log1p`, `exp`, `expm1`
- Other: `sqrt`, `abs`, `where`, `complex`, `real`, `imag`, `conj`

**Examples:**
- `exp(2) + sqrt(9)`
- `log(10) / 2`
- `where(5 > 2, 10, 0)`
- `sin(3.14/2) * 2`
- `abs(-7) + 5**2`
- `log1p(9)`
- `real(complex(3, 4))`
- `arctan2(1, 1)`
- `tanh(2) > 0.9`
    
    Args:
        expression: The nunexpr formatted expression to evaluate

    Returns:
        The result of the evaluation
    """
    try:
        return numexpr.evaluate(expression).item()
    except Exception as e:
        raise ValueError(f"Invalid or unsafe expression: {e}")

demo = gr.Interface(
    fn=safe_math_eval,
    inputs=gr.Textbox(label="Math Expression"),
    outputs=gr.Number(label="Result"),
    title="Safe Math Formula Evaluator",
    description=description
)

if __name__ == "__main__":
    demo.launch(mcp_server=True)