frontend / app.py
nagasurendra's picture
Update app.py
8758268 verified
import gradio as gr
# Backend function
def process_data(name, age):
if not name or not age:
return "Please provide both name and age."
return f"Hello {name}! You are {age} years old."
# HTML for the form
custom_html = """
<div>
<h2>Simple Form</h2>
<label for="name-field">Name:</label>
<input type="text" id="name-field" placeholder="Enter your name" />
<br /><br />
<label for="age-field">Age:</label>
<input type="number" id="age-field" placeholder="Enter your age" />
<br /><br />
<button onclick="submitForm()">Submit</button>
<p id="result" style="margin-top: 20px; font-size: 1.2em; color: green;"></p>
</div>
"""
# JavaScript for handling submission
custom_script = """
<script>
function submitForm() {
const name = document.getElementById('name-field').value;
const age = document.getElementById('age-field').value;
fetch('/api/predict', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
data: [name, age],
fn_index: 0 // Matches the backend function index
})
})
.then(response => response.json())
.then(data => {
document.getElementById('result').innerText = data.data[0]; // Show result
})
.catch(error => {
console.error('Error:', error);
document.getElementById('result').innerText = 'Failed to process the data.';
});
}
</script>
"""
# Gradio Interface for the backend
backend_interface = gr.Interface(
fn=process_data,
inputs=["text", "text"],
outputs="text"
)
# Main Gradio app
with gr.Blocks() as app:
with gr.Row():
gr.HTML("<h1>Interactive Form Example</h1>")
with gr.Row():
gr.HTML(custom_html)
with gr.Row():
gr.HTML(custom_script)
# Launching app and backend interface
app.queue() # Allow async queue
backend_interface.launch() # Ensure backend is running