sci-cal / app.py
Usually3's picture
Update app.py
481c83a
from fractions import Fraction
import gradio as gr
def calculator(num1, operation, num2=None):
if operation == "add":
return num1 + num2
elif operation == "subtract":
return num1 - num2
elif operation == "multiply":
return num1 * num2
elif operation == "divide":
return num1 / num2
elif operation == "square":
return num1 * num1
elif operation == "cube":
return num1 * num1 * num1
elif operation == "exponential":
return num1 ** num2
elif operation == "frac add":
return num1 + num2
elif operation == "frac subtract":
return num1 - num2
elif operation == "frac multiply":
return num1 * num2
elif operation == "frac divide":
return num1 / num2
# convert all inputs to fractions
num1 = Fraction(num1)
if num2 is not None:
num2 = Fraction(num2)
# convert result back to float if input was not a fraction
if isinstance(num1, float) or isinstance(num2, float):
return float(calculator(float(num1), operation, float(num2)))
else:
return num1
demo = gr.Interface(
fn=calculator,
inputs=[
gr.Number(value=4),
gr.Radio(["add", "subtract", "multiply", "divide", "square", "cube", "exponential", "frac add", "frac subtract", "frac multiply", "frac divide"]),
gr.Number(value=2, label="Second Number (optional)", optional=True)
],
outputs="number",
examples=[
[5, "add", 3],
[4, "divide", 2],
[-4, "multiply", 2.5],
[0, "subtract", 1.2],
[2, "exponential", 3],
[Fraction(1, 2), "frac add", Fraction(1, 3)],
[Fraction(3, 4), "frac subtract", Fraction(1, 5)],
[Fraction(2, 3), "frac multiply", Fraction(4, 5)],
[Fraction(3, 4), "frac divide", Fraction(1, 2)]
],
title="Scientific Calculator",
description="Here's a sample scientific calculator. Enjoy! Code by: Freddy Aboulton Improved by: Usually3 and ChatGpt"
)
demo.launch()