Spaces:
Sleeping
Sleeping
| # 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() | |