Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException
|
| 2 |
+
from pydantic import BaseModel
|
| 3 |
+
from typing import Optional, Union
|
| 4 |
+
import gradio as gr
|
| 5 |
+
|
| 6 |
+
app = FastAPI()
|
| 7 |
+
|
| 8 |
+
class OperationInput(BaseModel):
|
| 9 |
+
num1: Union[int, float]
|
| 10 |
+
num2: Union[int, float]
|
| 11 |
+
operation: str
|
| 12 |
+
|
| 13 |
+
@app.post("/calculate")
|
| 14 |
+
def calculate(input_data: OperationInput):
|
| 15 |
+
try:
|
| 16 |
+
num1 = input_data.num1
|
| 17 |
+
num2 = input_data.num2
|
| 18 |
+
operation = input_data.operation.lower()
|
| 19 |
+
|
| 20 |
+
if operation == "addition":
|
| 21 |
+
result = num1 + num2
|
| 22 |
+
elif operation == "subtraction":
|
| 23 |
+
result = num1 - num2
|
| 24 |
+
elif operation == "multiplication":
|
| 25 |
+
result = num1 * num2
|
| 26 |
+
elif operation == "division":
|
| 27 |
+
if num2 == 0:
|
| 28 |
+
raise HTTPException(status_code=400, detail="Division by zero is not allowed.")
|
| 29 |
+
result = num1 / num2
|
| 30 |
+
else:
|
| 31 |
+
raise HTTPException(status_code=400, detail="Invalid operation.")
|
| 32 |
+
|
| 33 |
+
return {"result": result}
|
| 34 |
+
|
| 35 |
+
except ValueError:
|
| 36 |
+
raise HTTPException(status_code=400, detail="Invalid input types.")
|
| 37 |
+
|
| 38 |
+
def calculator(num1, num2, operation):
|
| 39 |
+
response = calculate(OperationInput(num1=num1, num2=num2, operation=operation))
|
| 40 |
+
return response['result']
|
| 41 |
+
|
| 42 |
+
iface = gr.Interface(
|
| 43 |
+
fn=calculator,
|
| 44 |
+
inputs=["number", "number", "text"],
|
| 45 |
+
outputs="text",
|
| 46 |
+
title="Basic Arithmetic Operations",
|
| 47 |
+
description="Perform basic arithmetic operations: addition, subtraction, multiplication, and division.",
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
gr.mount_gradio_app(app, iface, path="/")
|
| 51 |
+
|
| 52 |
+
if __name__ == "__main__":
|
| 53 |
+
import uvicorn
|
| 54 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|