Spaces:
Running
Running
import gradio as gr | |
import rpy2.robjects as robj | |
from rpy2.robjects import default_converter | |
from rpy2.robjects.conversion import localconverter | |
# define R functions globally | |
robj.r(""" | |
add <- function(x,y) { return(x + y) } | |
multiply <- function(x,y) { return(x * y) } | |
sub <- function(x,y) { return(x - y) } | |
div <- function(x,y) { return(x / y) } | |
""") | |
def arithmetic(num1, num2, operation): | |
with localconverter(default_converter): | |
if operation == "Add": | |
res = robj.r(f"add({num1}, {num2})") | |
elif operation == "Multiply": | |
res = robj.r(f"multiply({num1}, {num2})") | |
elif operation == "Subtract": | |
res = robj.r(f"sub({num1}, {num2})") | |
elif operation == "Divide": | |
res = robj.r(f"div({num1}, {num2})") | |
return res[0] | |
# Custom CSS for better theme | |
custom_css = """ | |
body { | |
background-color: #121212; | |
color: #ffffff; | |
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; | |
} | |
/* Inputs and selects */ | |
input, textarea, select { | |
background-color: #1e1e1e; | |
color: #ffffff; | |
border: 1px solid #555; | |
border-radius: 6px; | |
padding: 8px; | |
} | |
/* Radio buttons */ | |
label input[type="radio"] { | |
accent-color: #3b82f6; | |
} | |
/* Buttons */ | |
button { | |
background: linear-gradient(135deg, #3b82f6, #0f4c81); | |
color: white; | |
border: none; | |
border-radius: 6px; | |
padding: 10px 20px; | |
cursor: pointer; | |
transition: background 0.3s ease; | |
} | |
button:hover { | |
background: linear-gradient(135deg, #60a5fa, #2563eb); | |
} | |
/* Result field styling */ | |
#result input { | |
background-color: #1e1e1e; | |
color: #00ffcc; | |
font-size: 1.5em; | |
border: 1px solid #444; | |
text-align: center; | |
} | |
/* Center heading text */ | |
h1, h3 { | |
text-align: center; | |
color: #ffffff; | |
} | |
/* Hide footer */ | |
footer { | |
display: none !important; | |
} | |
""" | |
with gr.Blocks( | |
title="R-Powered Calculator", | |
theme=gr.themes.Base(), | |
css=custom_css | |
) as app: | |
gr.HTML( | |
"<h1><strong>R-Powered Calculator</strong></h1>" | |
) | |
with gr.Row(): | |
num1 = gr.Number(label="Number 1") | |
num2 = gr.Number(label="Number 2") | |
with gr.Column(): | |
operation = gr.Radio( | |
choices=["Add", "Multiply", "Subtract", "Divide"], | |
value="Add", | |
label="Choose Arithmetic Operation", | |
min_width=100, | |
scale=0.3 | |
) | |
with gr.Row(): | |
submit = gr.Button("Run Operation") | |
with gr.Column(): | |
gr.HTML("<h2><strong>Arithmetic Operation Result</strong></h2>") | |
result = gr.Number(elem_id="result") | |
submit.click(arithmetic, inputs=[num1, num2, operation], outputs=[result]) | |
app.launch(server_name="0.0.0.0", server_port=7860) | |