Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# main.py
|
2 |
+
import gradio as gr
|
3 |
+
from fastapi import FastAPI, HTTPException
|
4 |
+
from pydantic import BaseModel
|
5 |
+
|
6 |
+
# FastAPI setup
|
7 |
+
app = FastAPI()
|
8 |
+
|
9 |
+
class CalculationRequest(BaseModel):
|
10 |
+
operation: str
|
11 |
+
x: float
|
12 |
+
y: float
|
13 |
+
|
14 |
+
@app.post("/calculate")
|
15 |
+
def calculate(request: CalculationRequest):
|
16 |
+
try:
|
17 |
+
if request.operation == "add":
|
18 |
+
answer = request.x + request.y
|
19 |
+
elif request.operation == "subtract":
|
20 |
+
answer = request.x - request.y
|
21 |
+
elif request.operation == "multiply":
|
22 |
+
answer = request.x * request.y
|
23 |
+
elif request.operation == "divide":
|
24 |
+
if request.y == 0:
|
25 |
+
raise HTTPException(status_code=400, detail="Division by zero is not allowed")
|
26 |
+
answer = request.x / request.y
|
27 |
+
else:
|
28 |
+
raise HTTPException(status_code=400, detail="Invalid operation")
|
29 |
+
|
30 |
+
return {"result": answer}
|
31 |
+
except ValueError:
|
32 |
+
raise HTTPException(status_code=400, detail="Invalid input types")
|
33 |
+
|
34 |
+
# Gradio interface
|
35 |
+
def perform_calculation(operation, x, y):
|
36 |
+
try:
|
37 |
+
x = float(x)
|
38 |
+
y = float(y)
|
39 |
+
except ValueError:
|
40 |
+
return "Error: Invalid input. Please enter numbers only."
|
41 |
+
|
42 |
+
request = CalculationRequest(operation=operation, x=x, y=y)
|
43 |
+
response = calculate(request)
|
44 |
+
return f"Result: {response['result']}"
|
45 |
+
|
46 |
+
demo = gr.Interface(
|
47 |
+
fn=perform_calculation,
|
48 |
+
inputs=[
|
49 |
+
gr.Dropdown(["add", "subtract", "multiply", "divide"], label="Operation"),
|
50 |
+
gr.Textbox(label="First Number"),
|
51 |
+
gr.Textbox(label="Second Number")
|
52 |
+
],
|
53 |
+
outputs="text",
|
54 |
+
title="Simple Calculator",
|
55 |
+
description="Enter two numbers and select an operation to perform a calculation."
|
56 |
+
)
|
57 |
+
|
58 |
+
# Run the application
|
59 |
+
if __name__ == "__main__":
|
60 |
+
demo.launch()
|