File size: 1,857 Bytes
46090e7
04e9088
46090e7
 
 
04e9088
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46090e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
04e9088
46090e7
04e9088
46090e7
 
 
 
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
# app.py (for Hugging Face Spaces deployment)

import gradio as gr

# Define the core calculator functions
def add(x, y):
    """Adds two numbers."""
    return x + y

def subtract(x, y):
    """Subtracts two numbers."""
    return x - y

def multiply(x, y):
    """Multiplies two numbers."""
    return x * y

def divide(x, y):
    """Divides two numbers. Handles division by zero."""
    if y == 0:
        return "Error! Division by zero."
    return x / y

# Gradio function to perform calculation based on operator
def calculate(num1, operator, num2):
    """
    Performs the selected arithmetic operation.
    Gradio will pass inputs as floats or strings, handle conversion.
    """
    try:
        num1 = float(num1)
        num2 = float(num2)
    except ValueError:
        return "Invalid input. Please enter valid numbers."

    if operator == '+':
        return add(num1, num2)
    elif operator == '-':
        return subtract(num1, num2)
    elif operator == '*':
        return multiply(num1, num2)
    elif operator == '/':
        return divide(num1, num2)
    else:
        return "Invalid operator selected."

# Create the Gradio interface
# We'll use a single function `calculate` and pass the operator as a dropdown
demo = gr.Interface(
    fn=calculate,
    inputs=[
        gr.Number(label="First Number"),
        gr.Dropdown(["+", "-", "*", "/"], label="Operation"),
        gr.Number(label="Second Number")
    ],
    outputs="text", # Output will be text (the result or an error message)
    title="Simple Gradio Calculator",
    description="Perform basic arithmetic operations in your browser."
)

# Launch the Gradio app
if __name__ == "__main__":
    # When deploying to Hugging Face Spaces, ensure you have a requirements.txt
    # with `gradio` listed.
    # For local testing, you can use demo.launch()
    demo.launch()