|
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) |
|
|