marcodsn commited on
Commit
2f05f1b
·
1 Parent(s): 80566e9

Added a safe math evaluator

Browse files
Files changed (1) hide show
  1. app.py +30 -4
app.py CHANGED
@@ -1,7 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
 
 
 
 
 
 
 
2
 
3
- def greet(name):
4
- return "Hello " + name + "!!"
 
 
 
 
 
5
 
6
- demo = gr.Interface(fn=greet, inputs="text", outputs="text")
7
- demo.launch()
 
1
+ description = """
2
+ Enter a math formula using the following operators and functions:
3
+
4
+ **Operators:** +, -, *, /, **, %, <, <=, ==, !=, >=, >, &, |, ~
5
+
6
+ **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
7
+
8
+ **Examples:**
9
+ - exp(2) + sqrt(9)
10
+ - log(10) / 2
11
+ - where(5 > 2, 10, 0)
12
+ - sin(3.14/2) * 2
13
+ """
14
+
15
  import gradio as gr
16
+ import numexpr
17
+
18
+ def safe_math_eval(expression: str) -> float:
19
+ try:
20
+ return numexpr.evaluate(expression).item()
21
+ except Exception as e:
22
+ raise ValueError(f"Invalid or unsafe expression: {e}")
23
 
24
+ demo = gr.Interface(
25
+ fn=safe_math_eval,
26
+ inputs=gr.Textbox(label="Math Expression"),
27
+ outputs=gr.Number(label="Result"),
28
+ title="Safe Math Formula Evaluator",
29
+ description=description
30
+ )
31
 
32
+ if __name__ == "__main__":
33
+ demo.launch(mcp_server=True)