Update app.py

#1
by asad231 - opened
Files changed (1) hide show
  1. app.py +60 -14
app.py CHANGED
@@ -1,22 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # app.py
2
  import gradio as gr
 
3
 
4
- # Define the calculator function
5
- def calculator(expression):
6
  try:
7
- result = eval(expression)
8
- return result
9
- except:
10
- return "Invalid input"
 
 
 
 
 
 
 
 
 
 
11
 
12
- # Create Gradio interface
13
  iface = gr.Interface(
14
- fn=calculator,
15
- inputs=gr.Textbox(label="Enter a math expression (e.g., 5 + 3 * 2)"),
16
- outputs=gr.Textbox(label="Result"),
17
- title="๐Ÿงฎ Calculator",
18
- description="This calculator can do addition (+), subtraction (-), multiplication (*), and division (/)."
 
 
 
 
 
 
 
 
 
 
 
19
  )
20
 
21
- # Launch the app
22
- iface.launch()
 
 
1
+ # # app.py
2
+ # import gradio as gr
3
+
4
+ # # Define the calculator function
5
+ # def calculator(expression):
6
+ # try:
7
+ # result = eval(expression)
8
+ # return result
9
+ # except:
10
+ # return "Invalid input"
11
+
12
+ # # Create Gradio interface
13
+ # iface = gr.Interface(
14
+ # fn=calculator,
15
+ # inputs=gr.Textbox(label="Enter a math expression (e.g., 5 + 3 * 2)"),
16
+ # outputs=gr.Textbox(label="Result"),
17
+ # title="๐Ÿงฎ Calculator",
18
+ # description="This calculator can do addition (+), subtraction (-), multiplication (*), and division (/)."
19
+ # )
20
+
21
+ # # Launch the app
22
+ # iface.launch()
23
+
24
  # app.py
25
  import gradio as gr
26
+ import math
27
 
28
+ # โœ… Safe Evaluation Function
29
+ def safe_eval(expression):
30
  try:
31
+ # Allowed functions and constants
32
+ allowed_names = {k: v for k, v in math.__dict__.items() if not k.startswith("__")}
33
+ allowed_names.update({
34
+ "abs": abs,
35
+ "round": round,
36
+ "pow": pow,
37
+ })
38
+
39
+ result = eval(expression, {"__builtins__": None}, allowed_names)
40
+ return f"โœ… Result: {result}"
41
+ except ZeroDivisionError:
42
+ return "โŒ Error: Division by zero"
43
+ except Exception as e:
44
+ return f"โŒ Error: Invalid expression"
45
 
46
+ # ๐ŸŽจ Gradio Interface
47
  iface = gr.Interface(
48
+ fn=safe_eval,
49
+ inputs=gr.Textbox(
50
+ label="๐Ÿ“ Math Expression",
51
+ placeholder="e.g. 8 + 2, 10 / 5, 3 * 4, sqrt(16), log(10), 5**2"
52
+ ),
53
+ outputs=gr.Textbox(label="๐Ÿ“Š Result"),
54
+ title="๐Ÿงฎ AI-Powered Calculator",
55
+ description=(
56
+ "๐Ÿ”ข This calculator supports:\n"
57
+ "- โž• Addition (+)\n"
58
+ "- โž– Subtraction (-)\n"
59
+ "- โœ–๏ธ Multiplication (*)\n"
60
+ "- โž— Division (/)\n"
61
+ "- ๐Ÿง  Math functions: sqrt(), log(), sin(), cos(), tan(), abs(), round(), pow()\n\n"
62
+ "โš ๏ธ Type only valid math expressions. No natural language."
63
+ )
64
  )
65
 
66
+ # ๐Ÿš€ Launch
67
+ if __name__ == "__main__":
68
+ iface.launch()