calculator / app.py
elsamueldev's picture
separated model, better type for `operation`
2e02765
raw
history blame
1.65 kB
# main.py
import gradio as gr
from fastapi import FastAPI, HTTPException
from models import CalculationRequest
# FastAPI setup
app = FastAPI()
@app.post("/calculate")
def calculate(request: CalculationRequest):
operation = request.operation.value
try:
if operation == "add":
answer = request.x + request.y
elif operation == "subtract":
answer = request.x - request.y
elif operation == "multiply":
answer = request.x * request.y
else: # only option left is divide
if request.y == 0:
raise HTTPException(status_code=400, detail="Division by zero is not allowed")
answer = request.x / request.y
return {"result": answer}
except ValueError:
raise HTTPException(status_code=400, detail="Invalid input types")
# Gradio interface
def perform_calculation(operation, x, y):
try:
x = float(x)
y = float(y)
except ValueError:
return "Error: Invalid input. Please enter numbers only."
request = CalculationRequest(operation=operation, x=x, y=y)
response = calculate(request)
return f"Result: {response['result']}"
demo = gr.Interface(
fn=perform_calculation,
inputs=[
gr.Dropdown(["add", "subtract", "multiply", "divide"], label="Operation"),
gr.Textbox(label="First Number"),
gr.Textbox(label="Second Number")
],
outputs="text",
title="Simple Calculator",
description="Enter two numbers and select an operation to perform a calculation."
)
# Run the application
if __name__ == "__main__":
demo.launch()