File size: 4,004 Bytes
8ee9804
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f8b9cf8
 
 
 
8ee9804
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8962ee2
 
dc5692b
 
8ee9804
dc5692b
8ee9804
 
f8b9cf8
8ee9804
 
 
dc5692b
8962ee2
8ee9804
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f8b9cf8
8196fba
f8b9cf8
8196fba
f8b9cf8
8ee9804
 
 
f8b9cf8
8ee9804
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
import gradio as gr
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

app = FastAPI()

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    if b == 0:
        return "Error: Division by zero"
    return a / b

def calculator(input_text):
    try:
        # Remove all spaces and then add spaces around operators
        input_text = input_text.replace(" ", "")
        for op in ['+', '-', '*', '/']:
            input_text = input_text.replace(op, f" {op} ")
        parts = input_text.split()
        if len(parts) != 3:
            return "Error: Invalid input"
        a = float(parts[0])
        op = parts[1]
        b = float(parts[2])
        if op == '+':
            return str(add(a, b))
        elif op == '-':
            return str(subtract(a, b))
        elif op == '*':
            return str(multiply(a, b))
        elif op == '/':
            return str(divide(a, b))
        else:
            return "Error: Invalid operator"
    except ValueError:
        return "Error: Invalid number"
    except Exception as e:
        return f"Error: {str(e)}"

def append_to_input(current, value):
    if current is None:
        current = ""
    current = str(current)  # Ensure current is a string
    value = str(value)  # Ensure value is a string
    if value in ['+', '-', '*', '/']:
        return f"{current} {value} "
    return current + value

def clear_input():
    return ""

def backspace(current):
    if current is None or current == "":
        return ""
    return current[:-1]

class CalculationInput(BaseModel):
    a: float
    b: float

@app.post("/add")
async def api_add(input: CalculationInput):
    return {"result": add(input.a, input.b)}

@app.post("/subtract")
async def api_subtract(input: CalculationInput):
    return {"result": subtract(input.a, input.b)}

@app.post("/multiply")
async def api_multiply(input: CalculationInput):
    return {"result": multiply(input.a, input.b)}

@app.post("/divide")
async def api_divide(input: CalculationInput):
    if input.b == 0:
        raise HTTPException(status_code=400, detail="Division by zero")
    return {"result": divide(input.a, input.b)}

@app.post("/calculate")
async def api_calculate(input: CalculationInput, operation: str):
    if operation == "+":
        return {"result": add(input.a, input.b)}
    elif operation == "-":
        return {"result": subtract(input.a, input.b)}
    elif operation == "*":
        return {"result": multiply(input.a, input.b)}
    elif operation == "/":
        if input.b == 0:
            raise HTTPException(status_code=400, detail="Division by zero")
        return {"result": divide(input.a, input.b)}
    else:
        raise HTTPException(status_code=400, detail="Invalid operation")

@app.get("/test")
async def test_route():
    return {"message": "FastAPI is working!"}

with gr.Blocks() as demo:
    input_text = gr.Textbox(label="Input", value="")
    output = gr.Textbox(label="Result")
    buttons = [
        ["7", "8", "9", "/"],
        ["4", "5", "6", "*"],
        ["1", "2", "3", "-"],
        ["0", ".", "=", "+"]
    ]
    for row in buttons:
        with gr.Row():
            for button in row:
                if button == "=":
                    gr.Button(button).click(calculator, inputs=input_text, outputs=output)
                else:
                    gr.Button(button).click(
                        lambda x, btn=button: append_to_input(x, btn),
                        inputs=[input_text],
                        outputs=input_text
                    )
    with gr.Row():
        clear_btn = gr.Button("Clear")
        backspace_btn = gr.Button("⌫")
    clear_btn.click(clear_input, inputs=[], outputs=input_text)
    backspace_btn.click(backspace, inputs=[input_text], outputs=input_text)

app = gr.mount_gradio_app(app, demo, path="/")

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=7860)