calculator / app.py
asad231's picture
Update app.py
5a3a0bb verified
raw
history blame
1.94 kB
# # app.py
# import gradio as gr
# # Define the calculator function
# def calculator(expression):
# try:
# result = eval(expression)
# return result
# except:
# return "Invalid input"
# # Create Gradio interface
# iface = gr.Interface(
# fn=calculator,
# inputs=gr.Textbox(label="Enter a math expression (e.g., 5 + 3 * 2)"),
# outputs=gr.Textbox(label="Result"),
# title="๐Ÿงฎ Calculator",
# description="This calculator can do addition (+), subtraction (-), multiplication (*), and division (/)."
# )
# # Launch the app
# iface.launch()
# app.py
import gradio as gr
import math
# โœ… Safe Evaluation Function
def safe_eval(expression):
try:
# Allowed functions and constants
allowed_names = {k: v for k, v in math.__dict__.items() if not k.startswith("__")}
allowed_names.update({
"abs": abs,
"round": round,
"pow": pow,
})
result = eval(expression, {"__builtins__": None}, allowed_names)
return f"โœ… Result: {result}"
except ZeroDivisionError:
return "โŒ Error: Division by zero"
except Exception as e:
return f"โŒ Error: Invalid expression"
# ๐ŸŽจ Gradio Interface
iface = gr.Interface(
fn=safe_eval,
inputs=gr.Textbox(
label="๐Ÿ“ Math Expression",
placeholder="e.g. 8 + 2, 10 / 5, 3 * 4, sqrt(16), log(10), 5**2"
),
outputs=gr.Textbox(label="๐Ÿ“Š Result"),
title="๐Ÿงฎ AI-Powered Calculator",
description=(
"๐Ÿ”ข This calculator supports:\n"
"- โž• Addition (+)\n"
"- โž– Subtraction (-)\n"
"- โœ–๏ธ Multiplication (*)\n"
"- โž— Division (/)\n"
"- ๐Ÿง  Math functions: sqrt(), log(), sin(), cos(), tan(), abs(), round(), pow()\n\n"
"โš ๏ธ Type only valid math expressions. No natural language."
)
)
# ๐Ÿš€ Launch
if __name__ == "__main__":
iface.launch()